ASP.NET MVC Routing – Constraints

MVC Routing Constraints allow for the application of a regular expression to a URL segment to determine if the route will match the request.

Previously in the introductory MVC Routing Tutorial we looked at defining Routes based on the number of segments in a URL. So the Route definition:

routes.MapRoute(“simple”, “{controller}/{action}/{id}“);

would match the URL /articles/category/12 . But suppose the content management system we are building also had a blog and we wanted to use URLs such as /2010/04/03. Such a URL would map to the simple Route we defined above and so in our example it would be processed as if it were referring to an article category.

Therefore we can see that just mapping URL segments to Route definitions is extremely limiting. Constraints allow for regex to be used to read the contents of the URL parameters to determine which Route definition to use. For example:

routes.MapRoute(“blogpost”, “{year}/{month}/{day}“
, new {controller=”blogpost”, action=”index”}
, new {year=@“\d{4}“, month=@“\d{2}“, day=@“\d{2}“});

routes.MapRoute(“simple”, “{controller}/{action}/{id}“);

Here there are two route definitions both of which have three parameters. Note the highlighted part of the blogpost route definition which is the definition of the constraint. The constraint in this case matches a URL of  4 digit number/2 digit number/2 digit number format. If this test is met the blogpost route definition will be applied, for all other 3 segment URLs the simple route definition will be applied.

Note the order of the definitions. ASP.NET MVC Routing attempts to match route definitions in sequence and once a match is made it is processed. Therefore, routes which contain constraints should always be placed before the simple non-constrained route definitions.

This entry was posted in Uncategorized by admin. Bookmark the permalink.

One thought on “ASP.NET MVC Routing – Constraints

  1. Pingback: ASP.NET 4.0 Routing Tutorial | ASP.NET 101

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>