With earlier version of ASP.NET MVC routing was strictly convention based and there was no way to give custom routes for specific controller and action associated with it. With ASP.NET MVC 5 and above attribute based routing feature was introduced. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web application. The earlier style of routing, called convention-based routing, is still supported and you can combine both techniques in the same controller and web application as well. To enable attribute routing, call MapMvcAttributeRoutes during configuration in RouteConfig.cs file
Now in the controller as part of action we can declare custom routes for each and every action
- For Index Action we have 3 routes set up and when we hit any of these 3 routes http://FQDN/Home/Test or http://FQDN/Home/Test1 or http://FQDN/Home/Test2 we will always hit the Index action.
- For About action the Url will be http://FQDN/Users/about.
- When you combine attribute routing with convention-based routing, actions which do not have Route attribute for defining attribute-based routing will work according to convention-based routing. In above example Contact action will work according to convention-based routing (http://FQDN/HOme/Contact).
You can set a common prefix for an entire controller by using the [RoutePrefix] attribute like show below
- Now in the above case for hitting Index action we have to use any of the following Url’s http://FQDN/Orders/Home/Test or http://FQDN/Orders/Home/Test1 or http://FQDN/Orders/Home/Test2
- For About action Url has to be http://FQDN/Orders/Users/about.
- All the routes where routing attribute has been spcified have to be prefixed with whatever common prefix declared at controller level (“Order” in this case). But the prefix does not get applied to convention based routing, so if we have to hit the contact action Url still remains the old one http://FQDN/Home/Contact.
When to use Attribute Routing
The convention-based routing is complex to support certain URI patterns that are common in RESTful APIs. But by using attribute routing you can define these URI patterns very easily. For example, resources often contain child resources like Clients have orders, movies have actors, books have authors and so on. It’s natural to create URIs that reflects these relations like as: /clients/1/orders. This type of URI is difficult to create using convention-based routing. Although it can be done, the results don’t scale well if you have many controllers or resource types. With attribute routing, it’s pretty much easy to define a route for this URI.
Similar attribute routing concept holds good for Web API 2