Use route constraints to restrict browser requests that match a specific route. You can use regular expressions to specify constraints.
For example, suppose you have defined the following route in the global. asax file of Code 1.
Code 1-Global. asax. CS
routes.MapRoute( "Product", "Product/{productId}", new {controller="Product", action="Details"} );
Code 1 restricts a route named product. You can use the product route to film browser requests to the constraint productcontroller, such as code 2.
Code 2-controllers/productcontroller. CS
Using system. web. MVC; <br/> namespace mvcapplication1.controllers <br/> {<br/> public class productcontroller: controller <br/>{< br/> Public actionresult details (INT productid) <br/>{< br/> return view (); <br/>}< br/>}
Note that the details () Action exposed by the product controller accepts a simple parameter named productid. This parameter is an integer parameter.
The routes defined in code 1 also match the following urls:
However, the route does not match the following URL:
- /Product/blah
- /Product/Apple
Because details () action requires an integer parameter, sending a request containing other things instead of an integer value will cause an error. For example, if you enter URL/product/apple in your browser, you will get the error 1.
Figure 01: The page is down (click to view the full size)
You only need to include the URL with a correct integer productid. You can use the constraint when defining a URL to restrict matching routes. Code 3 is the modified product route, which contains a regular expression constraint that only matches the integer.
Listing 3-Global. asax. CS
routes.MapRoute( "Product", "Product/{productId}", new {controller="Product", action="Details"}, new {productId = @"/d+" } );
The regular expression/d + matches one or more integers. This constraint makes the product route match the following URL:
However, the following URLs do not work:
These browser requests are processed by other routes, or, if no matching route existsResource not foundError.
Address: http://www.asp.net/learn/mvc/tutorial-24-cs.aspx