Choose Attribute Routing Instead Of Convention Based Routing In ASP.NET MVC

In this article, I will try to demonstrate you about when to choose Convention Based Routing and Attribute Routing.

In .NET technology, we have seen lot of different ways to hit some specific resource or URI. In ASP.NET, we use Url Rewriting where as in ASP.NET MVC, there are two more options, first one is Convention Based Routing and other one is Attribute Routing.

What is Convention Based Routing in ASP.NET MVC?

Routing is a mechanism which is used to handle the incoming requests coming from browsers and it represent the particular action rather than any static or physical files. In ASP.NET, the Url hits any resources or files which physically exists but ASP.NET MVC Routing represents action. It is an approach to perform some action based on their definition defined in RouteConfig.cs.

Convention Based Routing

  1. public static void RegisterRoutes(RouteCollection routes)  
  2. {  
  3.     routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  4.     routes.IgnoreRoute("favicon.ico");  
  5.     routes.IgnoreRoute("Content/img/dotnet-tutorial.ico");  
  6.     routes.MapRoute("LogOff""logOff"new  
  7.     {  
  8.         controller = "Account", action = "logoff"  
  9.     });  
  10.     routes.MapRoute("Register""register"new  
  11.     {  
  12.         controller = "Account", action = "Register"  
  13.     });  
  14.     routes.MapRoute("AboutUs""aboutus"new  
  15.     {  
  16.         controller = "Home", action = "AboutUs"  
  17.     });  
  18.     routes.MapRoute("IndividualArticlesPost""articles/{categoryslug}/{url}"new  
  19.     {  
  20.         controller = "Articles", action = "View"  
  21.     }, new  
  22.     {  
  23.         categoryslug = @ "\S+", url = @ "\S+"  
  24.     });  
  25.     routes.MapRoute("Default"// Route name  
  26.         "{controller}/{action}/{id}"// URL with parameters  
  27.         new  
  28.         {  
  29.             controller = "Home",  
  30.                 action = "Index",  
  31.                 id = UrlParameter.Optional  
  32.         });  
  33. }  
In the above code, you can see three things: “routes”, “IgnoreRoute” and “MapRoute”.

Routes: It is nothing but only a table which is a collection of routes defined in route table. When someone hits some url in the browser, application first check the existing routes table and match with routes.

IgnoreRoute: It is also a collection of url that should be ignored by application.

MapRoute: It is used to add new route into the route table.

routing

Attribute Routing

ASP.NET MVC also supports new type of routing that is called Attribute Routing. In this, attribute participate to route url to particular action.

To enable attribute routing, we need to use MapMvcAttributeRoutes() in the RouteConfig
  1. public class RouteConfig  
  2. {  
  3.     public static void RegisterRoutes(RouteCollection routes)  
  4.     {  
  5.         routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  6.         // Attribute Routing  
  7.         routes.MapMvcAttributeRoutes();  
  8.         // Convention Based Routing  
  9.         routes.MapRoute("LogOff""logOff"new  
  10.         {  
  11.             controller = "Account", action = "logoff"  
  12.         });  
  13.         routes.MapRoute("Register""register"new  
  14.         {  
  15.             controller = "Account", action = "Register"  
  16.         });  
  17.         routes.MapRoute("AboutUs""aboutus"new  
  18.         {  
  19.             controller = "Home", action = "AboutUs"  
  20.         });  
  21.         routes.MapRoute("IndividualArticlesPost""articles/{categoryslug}/{url}"new  
  22.         {  
  23.             controller = "Articles", action = "View"  
  24.         }, new  
  25.         {  
  26.             categoryslug = @ "\S+", url = @ "\S+"  
  27.         });  
  28.         routes.MapRoute("Default"// Route name  
  29.             "{controller}/{action}/{id}"// URL with parameters  
  30.             new  
  31.             {  
  32.                 controller = "Home",  
  33.                     action = "Index",  
  34.                     id = UrlParameter.Optional  
  35.             });  
  36.     }  
  37. }  
Attribute routing

Note: Attribute Routing is configuring before the Convention Routing or simple Routing.

We can use Convention based Routing and Attribute Routing in the same project. Be sure attribute routing should be defined first to convention based routing.
  1. public static void RegisterRoutes(RouteCollection routes)  
  2. {  
  3.     routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  4.     routes.MapMvcAttributeRoutes();  
  5.     routes.MapRoute(name: "Articles", url: "{controller}/{action}/{id}", defaults: new  
  6.     {  
  7.         controller = "Article", action = "Index", id = UrlParameter.Optional  
  8.     });  
  9.     routes.MapRoute(name: "Default", url: "{controller}/{action}/{id}", defaults: new  
  10.     {  
  11.         controller = "Home", action = "Index", id = UrlParameter.Optional  
  12.     });  
  13. }  
Sample Example

The following is a sample example of attribute routing. Here you can see we have used [Route] attribute to route the action with “Home/Index”. When we define the Route attribute, it added route to route table and mapped with specific action.
  1. public class ArticleController: Controller  
  2. {  
  3.     [Route("Home/Index")] //Route: /Home/Index  
  4.     public ActionResult Index()  
  5.     {  
  6.         return View();  
  7.     }  
  8. }  
Note: If route URI is not defined in attribute routing then it will work as Convention Routing.

Comman Route Prefix with Attribute Routing

To make your url neat, clear and user friendly, we can define the prefix in URL after domain name. We can use RoutePrefix attribute to define the prefix.
  1. [RoutePrefix("Articles")]  
  2. public class ArticleController: Controller  
  3. {  
  4.     [Route("{id}")] //Route: /Articles/13  
  5.     public ActionResult Details(int id)  
  6.         {  
  7.             //other code goes here  
  8.         }  
  9.         [Route("{username}")] //Route: /Articles/mukeshkumar  
  10.     public ActionResult MyArticleDetails(string username)  
  11.     {  
  12.         //other code goes here  
  13.     }  
  14. }  
Override the common route prefix with Attribute Routing

Sometimes, it is required to show different prefix in url with particular action. If you have already defined the Prefix for the whole controller then you can override it. To override the RoutePrefix, use ~ sign with prefix name with particular action in the Route attribute.
  1. [RoutePrefix("Articles")]  
  2. public class ArticleController: Controller  
  3. {  
  4.     [Route("~/ArticleList/{id}")] //Route: /ArticleList/13  
  5.     public ActionResult Details(int id)  
  6.     {  
  7.         //other code goes here  
  8.     }  
  9. }  
Route Constraints with Attribute Routing

When we use Route Constraints with Route attribute, it basically restrict or force how parameters will match.
  1. public class ArticleController: Controller  
  2. {  
  3.     [Route("Articles/{id:int}")] //Route: /Articles/13  
  4.     public ActionResult Details(int id)  
  5.         {  
  6.             //other code goes here  
  7.         }  
  8.         [Route("Articles/{username}")] //Route: /Articles/mukeshkumar  
  9.     public ActionResult GetUserDetails(string username)  
  10.     {  
  11.         //other code goes here  
  12.     }  
  13. }  
In the above code, if you pass integer value as parameter after “Articles/” then it will hit to first route otherwise second.

Attribute Routing in Area of ASP.NET MVC

In we are using Area in ASP.NET MVC project and want to use attribute routing, we need to use RouteArea attribute to define the area name and all will be same.
  1. [RouteArea("Admin")]  
  2. [RoutePrefix("Home")]  
  3. [Route("{action}")]  
  4. public class HomeController: Controller  
  5. {  
  6.     // route: /Admin/Home/Index  
  7.     public ActionResult Index()  
  8.         {  
  9.             return View();  
  10.         }  
  11.         // route: /Admin/Home/Employees  
  12.         [Route("employees")]  
  13.     public ActionResult GetEmployees()  
  14.         {  
  15.             return View();  
  16.         }  
  17.         // route: /department  
  18.         [Route("~/Department")]  
  19.     public ActionResult Departments()  
  20.     {  
  21.         return View();  
  22.     }  
  23. }  
Name attribute

As we use Custom Routing in ASP.NET MVC. We can achieve Custom Routing to define the Name of Route and use this route on the basis of Route name.
  1.  [Route("Articles", Name = "MyArticle")]  
  2.  public ActionResult GetAllArticle()  
  3.  {  
  4.  }  
  5. <a href="@Url.RouteUrl("MyArticle ")">My Article</a>  
Which One is the Best

As per our opinion, Attribute Routing provides us more flexibilities as compared to Convention Based Routing. In Attribute Routing, we can manage route as controller level, action level and also area level. Also, it can override the child route, if required.

This is only my opinion; you can try it and see which one is better.

Thanks for reading this article, hope you enjoyed it.