Attribute Routing in MVC
Attribute Routing in MVC
When we are using the [Route] attribute to define routes, it is called Attribute Routing. It provides us more control over the URIs by defining routes directly on actions and controllers in your ASP.NET MVC application.
How to use Attribute Routing:
Follow below steps to use attribute routing -
- First of all, enable the Attribute Routing in ASP.NET MVC Application for which we just need to add a call to routes.MapMvcAttributeRoutes() method within our RegisterRoutes() method of our RouteConfig.cs file.
Example –
namespace AttributeRouting
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//Enabling attribute routing
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
2. The next step is to decorate the action method with the Route attribute.
Example –
[HttpGet]
[Route("employees/{employeeID}/work")]
public ActionResult GetEmployeeData(int employeeID)
{
List WorkList = new List();
if (employeeID == 123456)
WorkList = new List() { "Design", "Development” };
else if (employeeID == 234567)
WorkList = new List() { "Design", "Development”, “Testing” };
else if (employeeID == 345678)
WorkList = new List() { "Design", "Development”, “Testing”, “Deployment” };
else
WorkList = new List() { "Design", "Development”, “Testing”, “Deployment”, “Sign Off” };
ViewBag.WorkList = WorkList;
return View();
}
Advantages of using Attribute Routing :
- It helps developer in the debugging by providing information about routes.
- It also reduces the chances for errors, because if a route is modified incorrectly in RouteConfig. cs then it may affect the entire application's routing which is not the case with attribute routing.
