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

How does route template precedence work when multiple routes could potentially match the same incoming URL?

Short answer

ASP.NET Core's routing system ranks candidate routes by specificity (more literal segments and constraints rank higher than wildcard/parameter segments), selecting the most specific match -- a route like /products/featured (fully literal) takes precedence over /products/{id}…

Save ASP.NET Core mock interview
Advertisement
AModel answer
ASP.NET Core's routing system ranks candidate routes by specificity (more literal segments and constraints rank higher than wildcard/parameter segments), selecting the most specific match -- a route like /products/featured (fully literal) takes precedence over /products/{id} (parameterized) for a request to /products/featured, ensuring the more specific, intentional route wins rather than an ambiguous match resulting in unpredictable behavior.
app.MapGet("/products/featured", () => GetFeaturedProducts());  // more specific, higher precedence
app.MapGet("/products/{id}", (string id) => GetById(id));         // less specific, lower precedence

// GET /products/featured matches the FIRST route despite also technically matching the second's pattern
Real-world example
An API correctly routes /products/featured to a dedicated featured-products handler instead of accidentally matching the more general /products/{id} pattern (which would try to parse 'featured' as an ID), thanks to ASP.NET Core's specificity-based precedence.
Likely follow-ups
  • What happens if two routes have identical specificity and both could match?
  • How do route constraints affect this precedence calculation?
Related topics