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:

download
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 ...

Get Professional ASP.NET MVC 3 now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.