Microsoft Learn

Route Constraints in ASP.NET Routing

This document provides a comprehensive overview of how to use route constraints in ASP.NET Routing to control which requests are matched by a specific route.

Understanding Route Constraints

Route constraints are an essential part of ASP.NET Routing. They allow you to define more specific matching criteria for your URLs beyond the basic pattern. By using constraints, you can ensure that a route is only considered if certain conditions are met, such as the format of a parameter or whether a parameter exists.

Constraints are typically defined as a dictionary where the key is the parameter name and the value is a string representing the constraint or a custom constraint object.

Common Constraint Types

1. Regular Expression Constraints

Regular expressions are widely used to validate the format of URL parameters. You can specify a regular expression pattern that the parameter's value must match.


new { controller = "Products", action = "Details", id = @"\d+" }
            

In this example, the id parameter must be one or more digits.

2. Built-in Constraints

ASP.NET Routing provides several built-in constraints for common scenarios:

These can be used directly in the route definition:


new { controller = "Users", action = "Profile", username = "alpha" }
            

3. Custom Constraints

For more complex validation logic, you can create custom constraint classes that implement the IRouteConstraint interface. This interface has a single method, Match, which returns true if the constraint is met, and false otherwise.


public class CustomConstraint : IRouteConstraint
{
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        // Your custom validation logic here
        // Example: Check if a value is greater than a certain number
        if (values.ContainsKey(parameterName))
        {
            if (int.TryParse(values[parameterName].ToString(), out int value))
            {
                return value > 100;
            }
        }
        return false;
    }
}
            

Then, register it with your route:


routes.MapPageRoute("CustomRoute", "items/{id}", "~/Views/Shared/Item.aspx",
    null,
    new RouteValueDictionary { { "id", new CustomConstraint() } });
            

Applying Constraints to Routes

Constraints are added to the defaults or constraints parameter when defining a route using MapRoute or MapPageRoute.

Tip: When defining multiple constraints for a parameter, they are combined using a logical AND.

Example: Combining Constraints

Let's say you want to match a product ID that is numeric and has a minimum length of 3:


routes.MapRoute(
    name: "ProductWithConstraints",
    url: "products/{productId}",
    defaults: new { controller = "Products", action = "Index" },
    constraints: new { productId = @"\d{3,}" } // Numeric and at least 3 digits
);
            

Example: Optional Parameters with Constraints

You can also apply constraints to optional parameters:


routes.MapRoute(
    name: "OptionalUserId",
    url: "users/{userId}",
    defaults: new { controller = "Users", action = "Profile", userId = UrlParameter.Optional },
    constraints: new { userId = @"\d+" } // If userId is present, it must be numeric
);
            
Important: Constraints are evaluated when the router attempts to match a URL against a defined route. If a constraint fails, that route is skipped, and the router tries the next available route.

Best Practices

By effectively using route constraints, you can build more robust and predictable URL routing for your ASP.NET applications.