Attribute routing in ASP.NET MVC 5+

Sheonarayan
Posted by in ASP.NET MVC category on for Advance level | Points: 250 | Views : 5453 red flag
Rating: 4.67 out of 5  
 3 vote(s)

In the previous article, we learnt about convention based routing. In this article, we shall learn about Attribute based routing that is directly applied to the action method of the controller. This feature is only supported in ASP.NET MVC 5+ versions.
Recommendation
Read Different types of routing in ASP.NET MVC before this article.

Introduction


We learnt about different types of convention based routing in the previous article. In this article, we shall learn about attribute based routing that is the major addition in ASP.NET MVC 5. Attribute based routing is implemented the way we implement any other attributes to the action method of the controller.


Important change to make in RouteConfig.cs


By default Attribute based routing is disabled in ASP.NET MVC. In order to enable it, we need to call MapMvcAttributeRoutes method of the RouteCollection object.

      public static void RegisterRoutes(RouteCollection routes)
        {

            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            // important to work with AttributeRouting in our RoutingStuffsController.cs
            routes.MapMvcAttributeRoutes();
      }

Calling above method instruct the routing system to inspect the Routing attributes in the controller classes apart from RouteConfig.cs settings.

Implementing Attribute Routing


To implement Attribute Routing, we use Route[] attribute in the action method of the controller.

 [Route("ITFunda")]
 public ActionResult AttributeRouting()
{
     return View("/Views/RoutingStuffs/ITFunda.cshtml");
}
In the above code snippet, we have specified  pattern of url to route to this action method of the controller. When we run our program and hit the url like below
  • http://localhost:63087/ITFunda
We see the /Views/RoutingStuffs/ITFunda.cshtml page as output in the browser.

Using Attribute Routing with Segment variables


Apart from just static URL (ITFunda), we can also mix string that contains static text as well as segment variables like this.

[Route("ITFunda/Show/{course}")]
public ActionResult AttributeRoutingParams(string course)
{
    ViewBag.Course = course;
    return View("/Views/RoutingStuffs/ShowCourse.cshtml");
}
In this case, if we browser the application with below url
  • http://localhost:63087/ITFunda/Show/ASPDOTNET
We get ShowCourse.cshtml page with course variable value as "ASPDOTNET". Remember that the segment variables name and action method parameter names must match to get the data from the url segment.

Constraining the segment variables

We can also constrain the segment variables like this

[Route("ITFunda/Show/{course:int}")] 

In this case, course segment must pass an integer value otherwise we get 404 error. So the correct url should look like http://localhost:63087/ITFunda/Show/10 not http://localhost:63087/ITFunda/Show/somestring

NOTE that we also need to change the corresponding action method parameter type.


Using RoutePrefix in the Controller class


We can also use RoutePrefix attribute in the controller class to define a common prefix to apply on all routes defined in the action methods of the controller.
 [RoutePrefix("IT")]
    public class RoutingStuffsController : Controller
    {

       [Route("ITFunda")]
        // UnComment the RouteConfig.cs - MapMvcAttributeRoutes();
        public ActionResult AttributeRouting()
        {
            return View("/Views/RoutingStuffs/ITFunda.cshtml");
        }

    }

After implementing RoutePrefix, the correct url would look like
  • http://localhost:63087/IT/ITFunda
Notice the /IT before /ITFunda because RoutePrefix is "IT".

Conclusion


Attribute based routing on one hand give flexibility to control the routing even at the controller level however on the other hand it defeats the ASP.NET MVC core purpose that is separation of concern. The routing mechanism is mixed in RouteConfig as well as Controller. With that said, the flexibility takes over and give us excellent control over URL management.

Hope you liked this article, do subscribe to the RSS feed at the top and let me know your feedback or comment.

Thanks
Recommendation
Read Custom authentication filter in ASP.NET MVC after this article.
Page copy protected against web site content infringement by Copyscape

About the Author

Sheonarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com
http://www.snarayan.com
Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Posted by: Goud.Kv on: 2/23/2015 | Points: 25
Simple, Well explained and Easy understandable........

Thanks

Login to post response

Comment using Facebook(Author doesn't get notification)