Advertisement
Intermediate ASP.NET Core, Endpoint Metadata, Route Constraints & Templates

How do route constraints (like {id:int} or {id:guid}) restrict which requests match a given route, and why are they useful?

Short answer

Route constraints, appended after a colon in the route parameter syntax, restrict matching to values satisfying a specific type or pattern -- {id:int} only matches numeric segments, {id:guid} only matches valid GUID strings, {slug:alpha} only matches alphabetic characters --…

Save ASP.NET Core mock interview
Advertisement
AModel answer
Route constraints, appended after a colon in the route parameter syntax, restrict matching to values satisfying a specific type or pattern -- {id:int} only matches numeric segments, {id:guid} only matches valid GUID strings, {slug:alpha} only matches alphabetic characters -- letting the routing system reject non-matching requests (falling through to another route or a 404) before the constraint mismatch ever reaches your handler as a confusing binding failure.
app.MapGet("/products/{id:int}", (int id) => GetById(id));       // only matches numeric IDs
app.MapGet("/products/{slug:alpha}", (string slug) => GetBySlug(slug));  // only matches alphabetic slugs

// GET /products/42 -> matches the first route
// GET /products/wireless-mouse -> matches the second route
Real-world example
An API distinguishes between numeric product IDs and human-readable slugs using route constraints, letting /products/42 and /products/wireless-mouse route to two entirely different handlers based purely on the URL's shape.
Likely follow-ups
  • What built-in constraints does ASP.NET Core provide (int, guid, alpha, minlength, etc.)?
  • How would you write a custom route constraint for a domain-specific pattern?
Related topics