AttributeRouting is an open source Nuget package which allows to specify routes using attributes in your controllers and actions.
Top Features
- Decorate your actions with GET, POST, PUT, DELETE, and verb agnostic attributes.
- Map multiple routes to a single action, ordering them with an Order property.
- Specify route defaults and constraints inline and also using attributes.
- Specify optional params inline with a token before or after the parameter name.
- Specify the route name for supporting named routes.
- Define MVC areas on a controller or base controller.
- Group or nest your routes together using route prefixes applied to a controller or base controller.
- Support legacy URLs.
- Set the precedence of routes among the routes defined for an action, within a controller, and among controllers and base controllers.
- Generate lowercase outbound URLs automatically.
- 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).
- 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