top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is Route Constraints in ASP.NET MVC?

+1 vote
403 views
What is Route Constraints in ASP.NET MVC?
posted Mar 23, 2017 by Jdk

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Creating Route Constraints

Suppose we have defined the following route in our application and you want to restrict the incoming request url with numeric id only.Now let's see how to do it with the help of regular expression.

routes.MapRoute(
 "Default", // Route name
 "{controller}/{action}/{id}", // Route Pattern
 new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Default values for parameters
);

Restrict to numeric id only

routes.MapRoute(
 "Default", // Route name
 "{controller}/{action}/{id}", // Route Pattern
 new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Default values for parameters
 new { id = @"\d+" } //Restriction for id
);

Now for this route, routing engine will consider only those URLs which have only numeric id like as http://example.com/Admin/Product/1 else it will considers that url is not matched with this route.
Creating Route Constraint to a Set of Specific Values
Suppose you want to restrict the user for those URLs that have controller name with H prefix and action name should be only Index or Contact. Now let's see how to do it with the help of regular expression.

routes.MapRoute(
 "Default", // Route name
 "{controller}/{action}/{id}", // Route Pattern
 new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Default values for parameters
 new { controller = "^H.*", action = "^Index$|^Contact$" } //Restriction for controller and action
);

Now for this route, routing engine will consider only those URLs which have controller name with H prefix and action name should be only Index or Contact like as http://example.com/Home/Index, http://example.com/Home/Contact and http://example.com,http://example.com/Home else it will considers that url is not matched with this route.
You are little bit confused why it will consider the http://example.com,http://example.com/Home URLs ?. It will also consider both these since route constraints is checked after the provided default values for controller and action. In above route default values for controller and action are Home and Index so these two URLs will also be matched. Like this you can restrict the user according to your need.

Note

Always put more specific route on the top order while defining the routes, since routing system check the incoming URL pattern form the top and as it get the matched route it will consider that. It will not checked further routes after matching pattern.

answer Mar 29, 2017 by Manikandan J
...