27
DecRoute Constraints in Asp.Net MVC with example
Route Constraints: An Overview
In the previous article, I described routingand how to create route in your application. Now the time is how to control the behavior of a route. Route constraints are a way to put some validation around the defined route. In this MVC Tutorial, we will explore more about Route Constraints which will include creating route constraints in asp.net mvc and understanding route constraints. Consider our ASP.NET MVC Course for a better understanding of all MVC core concepts.
Creating Route Constraints
Suppose we have defined the following route in our application and you want to restrict the incoming request URL with a 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, the routing engine will consider only those URLs that have numeric IDs like as http://example.com/Admin/Product/1 otherwise, it will consider that the 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 a controller name with an H prefix and the 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, the routing engine will consider only those URLs that have a controller name with an H prefix and the action name should be only Index or Contact.
You are a little bit confused as to why it will consider this URLs. It will also consider both these since route constraints are checked after the provided default values for controller and action. In the 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 needs.
Note
Always put more specific routes on the top order while defining the routes, since the routing system checks the incoming URL pattern from the top and as it gets the matched route it will consider that. It will not check further routes after the matching pattern.
Types of Route Constraints
1. IntConstraint
IntConstraint matches a 32-bit integer value.
Syntax:
2. BoolConstraint
Syntax
{ParameterName: bool}
3. DateTimeConstraint
Syntax
4. DecimalConstraint
Syntax
5. DoubleConstraint
Syntax
6. FloatConstraint
Syntax
7. GuidConstraint
Syntax
8. LongConstraint
Syntax
9. MaxLengthRouteConstraint
MaxLengthRouteConstraint matches a string with a maximum value.
Syntax
10. MinLengthRouteConstraint
Syntax
Route Constraints with example:
public class HomeController : Controller
{
// URL: /Mvctest/1
[Route(“Mvctest /{ customerId:int}”)]
public ActionResult GetCutomerById(int customerId)
{
ViewBag.Message = "Welcome to ScholarHat!";
return View();
}
// URL: /Mvctest/{customerName}
[Route(“Mvctest /{ customerName}”)]
public ActionResult GetCutomerByName(string customerName)
{
ViewBag.Message = "Welcome to ScholarHat!";
return View();
}
}
Multiple constraints Example:
/ URL: /Mvctest/1 à Action method is not be selected
// URL: /Mvctest/1001 à Action method is selected
[Route(“Mvctest /{ customerId:int:min(1000)}”)]
public ActionResult GetCutomerById(int customerId)
{
ViewBag.Message = "Welcome to Scholarhat!";
return View();
}