Asp.Net MVC Attribute Routing

Asp.net MVC Routing determines the appropriate actions, controllers and  data for any incoming request specified in a format or a group of format sent to parse the URL’s.Routing rather than having concrete physical files uses abstract actions.


This is achieved mostly by Convention Routing. Asp.net MVC 5 as another scheme called Attribute Routing. Attribute routing helps to keep the routing definition at the close proximate of actions and controllers. This similar to Convention Routing adds the routes to Route Table. 

Enabling Attribute Routing

Use MapMvcAttributeRoutes() as shown in below code sample. This enables both Convention and Attribute routing

 public static void RegisterRoutes(RouteCollection routes)  
     {  
       routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
       routes.MapMvcAttributeRoutes();  
       routes.MapRoute(  
         name: "Default",  
         url: "{controller}/{action}/{id}",  
         defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }  
       );  
     }  

Following example shows usage of Attribute Routing :-

 [Route("SingleStringParam/{FirstParam}")]  
     public ActionResult OneStringParameter(string FirstParam)  
     {  
       ViewBag.FirstParameter = FirstParam;  
       return View();  
     }  

For nullable parameters use ? in front of parameter:-

[Route("SingleStringOptionalParam/{FirstParam?}")]  
     public ActionResult OneStringOptionalParameter(string FirstParam)  
     {  
       ViewBag.FirstParameter = FirstParam;  
       return View();  
     }  
   }  

What is better – Convention or Attribute routing, my opinion-
Attribute routing is more flexible than Convention routing as it is easy to maintain and close to the actions and controllers. Instead of managing whole list of routes in route.config, tedious to maintain, use attribute routing. As attribute routing are close to Controller Action it helps in debugging and troubleshooting, as well as ability to quickly search the route information in your solution.

Reference- Attribute Routing

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s