Route Constraints in MVC:-

We will understand the routing constraints using example. Consider two url mention below

  1. http://localhost:10200/Home/Employee/14
  2. http://localhost:10200/2005/02/02

Each url has three segments and each will map to the default route. But does it mean that second url has Controller with name “2005Controller” and method as “02”?. No, it really meant the different meaning, not all the segments mention in the url should match the Controller and action method name.

Consider below route mapping, where second URL map to the “SimpleRoute”, where url is accepted as "{year}/{month}/{day}" format. Constraints allow you to use the regular expression to define the url pattern.

       
    public static void RegisterRoutes(RouteCollection routes)
        {         

            routes.MapRoute(
                name: "SimpleRoute",
                url: "{year}/{month}/{day}",
                defaults: new { controller = "blog", action = "index" },
                constraints: new { year = @"\d{4}", month = @"\d{2}", day = @"\d{2}" }
                );

            routes.MapRoute(
               name: "Default",
               url: "{controller}/{action}/{id}",
               defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
           );
        }
    
    

Example of multiple Patterns with matching routes

Route URL Request URL Route data result
{filename}.{ext} /Foo.xml.aspx Filename = “foo.xml” , Ext= “aspx”
My{title}-{cat} /MyHouse-coimbatore Location=”House” , Sublocation =” coimbatore”
{foo}xyz{bar} /xyzxyzxyzabcd Foo=”xyzxyz” , Bar=”abcd”