ASP.NET MVC 5 Route Attributes

Step by step Microsoft has switched their main web technology during the last few years. Web Forms with its component model is now replaced by the Model-View-Controller design pattern. Web Forms is not deprecated yet, but my personal opinion is that it is just a matter of time. The main reason of keeping that technology alive is the fact many CMS-es are built on top of it. Once these systems fully support MVC and switch their main stream to it, Web Forms will follow the faith of it`s fellow WinForms.

Microsoft gave another way of managing URL routes with the 5-th main release of MVC. Since now all the routes or route patterns were declared in RouteConfig.cs. May be keeping every route related data at one place is a good practice but in most of the cases this file gets too big to be supported easily. With the new MVC release Microsoft allowed us to manage the URLs directly in the controller using Routing Attributes. Of course MVC is backward compatible and the other way is still supported.

To start using Routing Attributes we should map them. To do this we need to put the line

routes.MapMvcAttributeRoutes();

in Register Routes Method in RouteConfig.cs file:

Let`s register the first route:

The usage is very simple and intuitive. Have in mind that the name parameter is optional. As you probably know the name of a route is used with the Html and Url helpers like Html.ActionLink , Url.Action etc.

The route prefix for the entire controller can be set using RoutePrefix attribute. If the route prefix parameter is not set the route will take its default path defined in RouteConfig.cs.
Another point of interest here is the Route attribute used for the controller. In this case route defines the default action for the controller route. In most of the cases that is the index action but theoretically it can be every other action.

Having route prefix set for the controller we can very easily override it for an action route. This can be done using a tilde (~) in the beginning of the route:

Sometimes we need an action parameter to be optional. We can achieve that by adding a question mark to the route parameter.

When using attributes for managing routing we can set some constraints that restrict how the parameters in the route template are matched. For example we can restrict a parameter to be integer:

In this case the parameter id must be integer. If something else is passed the server will throw 404 error.

Even more interesting example of using parameter restrictions is the range constraint.

In the example the age parameter must be integer between 18 and 19.

One of my favorite usages of routing is the catch-all route URL segment. It is valid even in the old route approach but most of the developers do not know about it.

This route will match any URL after the action route: in other words path will match everything after content-item part of the URL. This approach is very useful when you pass paths in the URL.