Asp.net MVC routing using Attributes

AttributeRouting is an open source Nuget package which allows to specify routes using attributes in your controllers and actions.

Top Features

  1. Decorate your actions with GET, POST, PUT, DELETE, and verb agnostic attributes.
  2. Map multiple routes to a single action, ordering them with an Order property.
  3. Specify route defaults and constraints inline and also using attributes.
  4. Specify optional params inline with a token before or after the parameter name.
  5. Specify the route name for supporting named routes.
  6. Define MVC areas on a controller or base controller.
  7. Group or nest your routes together using route prefixes applied to a controller or base controller.
  8. Support legacy URLs.
  9. Set the precedence of routes among the routes defined for an action, within a controller, and among controllers and base controllers.
  10. Generate lowercase outbound URLsĀ  automatically.
  11. Define your own custom route conventions and apply them on a controller to generate the routes for actions within the controller without boilerplate attributes (think RESTful style).
  12. Debug your routes using a supplied HttpHandler.

Installing

In Nuget package manager console type the below line :


Install-Package AttributeRouting

Usage


public class ProductsController : Controller
{
[GET("Products")]
public ActionResult Index()
{
return View();
}

[GET("Products/New")]
public ActionResult New()
{
return View();
}

[POST("Products")]
public ActionResult Create()
{
return RedirectToAction("Index");
}

[GET("Resources/{id}")]
public ActionResult Show(int id)
{
return View();
}

[GET("Products/{id}/Edit")]
public ActionResult Edit(int id)
{
return View();
}

[PUT("Resources/{id}")]
public ActionResult Update(int id)
{
return RedirectToAction("Show");
}

[GET("Products/{id}/Delete")]
public ActionResult Delete(int id)
{
return View();
}

[DELETE("Products/{id}")]
public ActionResult Destroy(int id)
{
return RedirectToAction("Index");
}
}

in order to make the above code working you need to have the RoutingAttributes library to find them and create corresponding routes in routes table. make the below changes in the global.asax


public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapAttributeRoutes();
}

if you have installed this package via Nuget, you will have a file in app_start folder that will call this registration hook automatically