Attribute Routing in ASP.NET MVC 5

ASP.NET MVC 5 introduced Attribute Routing. It allows you to apply a route directly on the controller class. Before we use the Attribute Routing, let’s relook how the convention based routing works.

We create a route as follows:

clip_image002

Index action of Home controller can be accessed on two different URLs. Either using the base URL (default value is set) or using baseurl/Home/Index as shown below:

clip_image004

In convention based routing action is accessed using the baseurl/controllername/actionname. Using the Attribute Routing this behaviour can be overridden. To use attribute routing you need to enable it in RouteConfig. To enable it, in the RoutConfig.cs call routes.MapMvcRouteAttribute() method.

clip_image006

Once it is enabled you can apply attribute routing on action using Route attribute and passing a value in this.

clip_image008

Now Index action can be access on the URL: baseurl/Test

clip_image010

You can also pass parameters in the attribute route. Parameters name and variables in route value must be the same.

clip_image012

Index action can be access with parameter values as shown below- I am passing 40 as value of age and steve as value of name.

clip_image014

You may want to use the attribute routing in your project as per the requirement. Keep in mind that attribute routing and the convention based routing can be used together.

Happy coding.

Leave a comment

Create a website or blog at WordPress.com