Custom Route Constraints in ASP.Net MVC 5

Introduction

Attribute Routing is introduced in MVC 5.0. We can also define parameter constraints by placing a constraint name after the parameter name separated by a colon. There are many builtin routing constraints available. We can also create custom routing constraints.

To create a custom route constraint, we have implemented our class from an IRouteConstraint interface. It is a very simple interface and contains the single method: Match. This method returns a Boolean value. If we return false from this method then the route associated with the constraint would not match the request.

Definition of IRouteConstraint interface

  1. public interface IRouteConstraint  
  2. {  
  3.     bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection);  
  4. } 

Example of creating custom Route Constraint

In the following example, I created a simple custom route constraint that always returns true. Here the CustomRouteConstraint class implemented from the IRouteConstraint interface.

  1. public class CustomRouteConstraint : IRouteConstraint  
  2. {  
  3.     public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)  
  4.     {  
  5.         return true;  
  6.     }  
  7. } 

Custom Route Constraint with parameter

We can also create a Route constraint with a parameter just like length, max, min and so on route constraint.

In the following example, I created a custom a route constraint with a parameter. It accepts a parameter value as an argument and it compares an input value (input by URL) and parameter value and based on this it returns either true or false.

Example

  1. public class CustomRouteWithParameterConstraint : IRouteConstraint  
  2. {  
  3.   
  4.     private readonly string _parameterValue;  
  5.      public CustomRouteWithParameterConstraint(string parameteValue)  
  6.     {  
  7.         _parameterValue = parameteValue;  
  8.     }   
  9.   
  10.     public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)  
  11.     {  
  12.         object value;  
  13.         if (values.TryGetValue(parameterName, out value) && value != null)  
  14.         {  
  15.             if (value.ToString() == _parameterValue)  
  16.             {  
  17.                 return true;  
  18.             }  
  19.         }  
  20.         return false;  
  21.     }  
  22. } 

Register Custom Route constraint

Before use a custom route constraint, we need to register it whenever the application starts. Using the following code we can register the custom route constraint in the RegisterRoutes method of the RouteConfig class.

  1. public class RouteConfig  
  2. {  
  3.     public static void RegisterRoutes(RouteCollection routes)  
  4.     {  
  5.         routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  6.         var constraintsResolver = new DefaultInlineConstraintResolver();  
  7.         constraintsResolver.ConstraintMap.Add("CustomRoute"typeof(CustomRouteConstraint));  
  8.         constraintsResolver.ConstraintMap.Add("CustomRouteWithParameter"typeof(CustomRouteWithParameterConstraint));  
  9.         routes.MapMvcAttributeRoutes(constraintsResolver);  
  10.     }  
  11. }
Note: when you add custom route constraint in ConstraintMap dictionary, name of key is same as class name of custom route constraint.

How to use customize a route constraint

A custom route constraint can be also used in the same way as a builtin route constraint is used.

Example

  1. [Route("MvcTest/other/{name:CustomRoute}")]  
  2. public ActionResult OtherPage(string name)  
  3. {  
  4.     return View();  
  5. }  
  6. [Route("Mvctest/{name:CustomRouteWithParameter(test)}")]  
  7. public ActionResult Index(string name)  
  8. {  
  9.     return View();  
  10. } 

Use custom Route constraint with Convention-Based Routing

A custom route constraint can also be used with a Convention based routing. The new version MVC has an override version MapRoute method that accepts a constraint as a parameter. Using this method we can pass over a custom constraint.

  1. public static Route MapRoute(this RouteCollection routes, string name, string url, object defaults, object constraints);   

Example

  1. routes.MapRoute(name: "newRoute",  
  2.         url: "Mvctest/{name}",  
  3.         defaults: new { controller = "Home", action = "Index" },  
  4.         constraints: new { name = new CustomRouteWithParameterConstrain("test") }  
  5. );  
  6. routes.MapRoute(name: "newRoute1",  
  7.       url: "Mvctest/other/{name}",  
  8.       defaults: new { controller = "Home", action = "OtherPage" },  
  9.       constraints: new { name = new CustomRouteConstrain() }  
  10. ); 

Summary

Using the preceding described method, we can create a custom route constraint.


Similar Articles