Adds a route constraint for validating string path parameters at the routing layer.
Steps
- Create
src/backend/MyProject.WebApi/Routing/{Name}RouteConstraint.cs:public partial class {Name}RouteConstraint : IRouteConstraint { public bool Match(HttpContext? httpContext, IRouter? route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection) { if (!values.TryGetValue(routeKey, out var value) || value is not string s) return false; return s.Length <= 100 && Pattern().IsMatch(s); } [GeneratedRegex(@"^[A-Za-z0-9._-]+$")] private static partial Regex Pattern(); } - Register in
Program.csinsideAddRouting:options.ConstraintMap.Add("myConstraint", typeof({Name}RouteConstraint)); - Use in routes:
[HttpGet("items/{id:myConstraint}")] - Non-matching routes return 404 automatically - no controller code needed
- Verify:
dotnet build src/backend/MyProject.slnx
Source: fpindej/netrock — distributed by TomeVault.