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
- public interface IRouteConstraint
- {
- bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection);
- }
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.
- public class CustomRouteConstraint : IRouteConstraint
- {
- public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
- {
- return true;
- }
- }
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
- public class CustomRouteWithParameterConstraint : IRouteConstraint
- {
- private readonly string _parameterValue;
- public CustomRouteWithParameterConstraint(string parameteValue)
- {
- _parameterValue = parameteValue;
- }
- public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
- {
- object value;
- if (values.TryGetValue(parameterName, out value) && value != null)
- {
- if (value.ToString() == _parameterValue)
- {
- return true;
- }
- }
- return false;
- }
- }

Upendra Pratap ShahiPosted Oct 3, 2017, 12:52 PM
How can I achieve test.upendra.com call action method as call on upendra.com?
Ian DavisPosted May 19, 2015, 8:31 AM
How do you create a custom constraint for attribute routing that is not attached to a parameter? For example, it just does a check on the current host, and is a Match if the host is example.com