Tuesday, 30 July 2013

Restrict to numeric id only in mvc routing

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://abc.com/Admin/Product/1 else it will considers that url is not matched with this route.