How would you implement a custom route constraint (IRouteConstraint) for a domain-specific validation pattern, like a product SKU format?
Short answer
Implement IRouteConstraint's Match method containing the custom matching logic (like a regex check against a specific SKU pattern), register it with a name in the RouteOptions.ConstraintMap, and reference it in route templates via that name -- letting invalid-format URLs fail to…
Advertisement
AModel answer
Implement IRouteConstraint's Match method containing the custom matching logic (like a regex check against a specific SKU pattern), register it with a name in the RouteOptions.ConstraintMap, and reference it in route templates via that name -- letting invalid-format URLs fail to match at the routing level rather than reaching the handler and requiring manual validation there.
public class SkuConstraint : IRouteConstraint {
public bool Match(HttpContext? context, IRouter? route, string routeKey, RouteValueDictionary values, RouteDirection direction) {
return values.TryGetValue(routeKey, out var value) &&
Regex.IsMatch(value?.ToString() ?? "", @"^[A-Z]{3}-\d{4}$");
}
}
builder.Services.Configure<RouteOptions>(options => options.ConstraintMap.Add("sku", typeof(SkuConstraint)));
app.MapGet("/products/{sku:sku}", (string sku) => GetBySku(sku));Real-world example
A warehouse inventory API rejects malformed SKU-format URLs (like /products/invalid) at the routing level using a custom constraint, before the request ever reaches handler code that would otherwise need to manually validate and reject the malformed input.
Likely follow-ups
- How does a custom route constraint's performance compare to validating inside the handler?
- What's the risk of overly complex regex logic inside a route constraint?
Related topics