BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News Attribute Based Routing in ASP.NET MVC

Attribute Based Routing in ASP.NET MVC

Bookmarks

In ASP.NET MVC 4 and earlier routing was handled exclusively via adding paths to a RouteCollection. Though is starts with simple convention based routing, as a website grows and the special cases accumulate it can become quite complex. And since the routes are physically separated from the controllers they apply to, it can take some detective work to understand the relationships.

With the introduction of ASP.NET MVC 5, Microsoft hopes to simplify the experience using attribute-based routing. Using the same basic pattern syntax as the imperative model, a declarative Route attribute can be applied to controller methods.

To specify a default route for a given controller, simply add the Route attribute to the class with the path “{action=method}” where “method” is the name of the default method. You can also apply a RoutePrefix attribute to a controller, which reduces the length of the paths contained by the controller. Area registration can also be eliminated using attributes, in this case the RouteArea attribute.

These routes support constraints, optional URI parameters, and default values. MVC constraints follow the same rules as Web API’s attribute based routing.

Rate this Article

Adoption
Style

BT