Route constraints are an essential tool in ASP.NET Core routing that allows you to add extra validation to your route parameters. They define rules that restrict the values a parameter can accept, helping you filter out invalid requests before they reach your endpoint handlers.
Common Route Constraints ASP.NET Core provides a variety of built-in route constraints: int: Requires the parameter value to be an integer. bool: Requires the parameter value to be a boolean (true or false). datetime: Requires the parameter value to be a valid date and time string. decimal, double, float, long: Require the parameter value to be of the specified numeric type. guid: Requires the parameter value to be a valid GUID (Globally Unique Identifier). alpha: Requires the parameter value to consist only of alphabetic characters (a-z, A-Z). regex: Requires the parameter value to match a regular expression pattern. length: Requires the parameter value to have a specific length or within a specified range. min, max, range: Require the parameter value to be greater than or equal to the minimum (min), less than or equal to the maximum (max), or within a specific range (range). Code // … (UseRouting and other middleware) …
Alphabetic and Length Constraint: /employee/profile/{EmployeeName:length(4,7):alpha=harsha}: Ensures EmployeeName is 4-7 characters long and consists only of alphabetic characters. If not supplied, it defaults to “harsha”. Integer, Range, and Optional Constraint: /products/details/{id:int:range(1,1000)?}: Requires id to be an integer between 1 and 1000. The question mark makes it optional. DateTime Constraint: /daily-digest-report/{reportdate:datetime}: Requires reportdate to be a valid date-time string. GUID Constraint: /cities/{cityid:guid}: Requires cityid to be a valid GUID. Integer, Min, and Regex Constraint: /sales-report/{year:int:min(1900)}/{month:regex(^(apr|jul|oct|jan)$)}: Requires year to be an integer greater than or equal to 1900, and month to be one of the specified values (apr, jul, oct, jan).