In ASP.NET MVC, Route Constraints are used to restrict the values that a route parameter can accept. They help ensure that only valid URLs match a particular route by applying specific conditions on route parameters.
By default, MVC routes match any value for a parameter. However, in some cases, you might want to allow only certain types of values. For example:
Route constraints are applied within the MapRoute method using curly braces {} after the parameter name. Constraints are specified using a colon (:) followed by the constraint type.
namespace FirstMVCDemo
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default", //Route Name
url: "{controller}/{action}/{id}", //Route Pattern
defaults: new
{
controller = "Home", //Controller Name
action = "Index", //Action method Name
id = UrlParameter.Optional //Defaut value for above defined parameter
}
);
}
}
}
An alternative overload of the MapRoute method allows us to define constraints as an additional parameter. Using this approach, we can apply a regular expression to validate the incoming route parameters.
In the example below, we specify a constraint for the id parameter using new { id = @"\d+" } as the fourth argument in the MapRoute method. This ensures that only numeric values are accepted for the id parameter.
If a non-numeric value is provided in the URL, the request will either be handled by another defined route or, if no matching routes are found, an error message stating "The resource could not be found" will be displayed.
With this restriction in place, the routing engine will only process URLs where the id parameter contains numeric values, such as:
http://dotnettutorials.com/Home/Index/10
namespace FirstMVCDemo
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default", //Route Name
url: "{controller}/{action}/{id}", //Route Pattern
defaults: new
{
controller = "Home", //Controller Name
action = "Index", //Action method Name
id = UrlParameter.Optional //Defaut value for above defined parameter
},
constraints :new { id = @"\d+" } //Restriction for id
);
}
}
}
Now you want to limit the incoming request URL to contain only a numeric ID. Let’s explore how to achieve this using a regular expression in an ASP.NET MVC application.
you can use regular expressions to restrict access to certain controllers and actions. For instance, if you want to allow only those URLs where the controller name begins with "H" and the action is either "Details" or "About," you can achieve this using a regex pattern. Let’s see how to implement this.
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
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 = "^Details$|^About$" } //Restriction for controller and action
);
}
}
With this route configuration, the routing engine will only match URLs where the controller name starts with "H" and the action is either "Details" or "Index. " For example, URLs like http://aitaurangabad.com/Home/Index, http://aitaurangabad.com/Home/Details, http://aitaurangabad.com/, and http://aitaurangabad.com/Home will be considered valid. Any other URLs will not match this route. You might wonder why http://aitaurangabad.com/ and http://aitaurangabad.com/Home are also included. This happens because route constraints are applied after default values are assigned. In this case, the default controller is "Home" and the default action is "Index," so these URLs still conform to the rule. This approach allows you to control access based on your specific requirements.
Many developers often compare routing with URL rewriting, as both contribute to creating SEO-friendly URLs and appear similar. However, they serve different purposes: