Custom Route Constraints
The “Route Constraints” section earlier in this chapter covered how to use regular expressions to provide fine-grained control over route matching. As you might recall, we pointed out that the RouteValueDictionary class is a dictionary of string-object pairs. When you pass in a string as a constraint, the Route class interprets the string as a regular expression constraint. However, it is possible to pass in constraints other than regular expression strings.
Routing provides an IRouteConstraint interface with a single Match method. Here's a look at the interface definition:
public interface IRouteConstraint
{
bool Match(HttpContextBase httpContext, Route route, string parameterName,
RouteValueDictionary values, RouteDirection routeDirection);
}
Code snippet 9-19.txt
When routing evaluates route constaints, and a constraint value implements IRouteConstraint, it will cause the route engine to call the IRouteConstraint.Match method on that route constraint to determine whether or not the constraint is satisfied for a given request.
Routing itself provides one implementation of this interface in the form of the HttpMethodConstraint class. This constraint allows you to specify that a route should match only a specific set of HTTP methods (verbs).
For example, if you want a route to respond only to GET requests, but not POST, PUT, or DELETE requests, you ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access