Custom Route Constraint Classes in Asp.net Core

Custom Route Constraint Classes in Asp.net Core
ASP.NET Core offers a variety of built-in route constraints, sometimes your application requires more specialized validation rules. Custom route constraint classes allow you to define your own criteria for determining whether a parameter value is valid.
Key Requirements
Implement IRouteConstraint: Create a class that implements the IRouteConstraint interface.
Match Method: Implement the Match method, which will contain your custom validation logic. This method receives several parameters:
httpContext: The current HttpContext.
route: The IRouter object associated with the route.
routeKey: The name of the route parameter being validated.
values: A dictionary containing the route values.
routeDirection: Indicates whether the route is being matched for an incoming request or for generating a URL.
Return true or false: The Match method must return true if the parameter value is valid according to your constraint, and false otherwise.
 
Code
// MonthsCustomConstraint.cs
public class MonthsCustomConstraint : IRouteConstraint
{
    public bool Match(HttpContext? httpContext, IRouter? route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
    {
        // Check if the parameter value exists
        if (!values.ContainsKey(routeKey))
        {
            return false; // Not a match
        }
 
        Regex regex = new Regex(“^(apr|jul|oct|jan)$”);
        string? monthValue = Convert.ToString(values[routeKey]);
 
        if (regex.IsMatch(monthValue))
        {
            return true; // It’s a match
        }
        return false; // Not a match
    }
}

Using the Custom Constraint
// … (in your endpoint configuration) …
endpoints.Map(“sales-report/{year:int:min(1900)}/{month:months}”, async context =>
{
    // … your endpoint handler logic …
});
 
Notice the :months constraint after the month parameter. This indicates that the value for month should be validated against the MonthsCustomConstraint class.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply