8.7 — Endpoint Selection and Precedence¶
← Roadmap · Section: 8. Routing Prev: 8.6 Link generation · Next: 8.8 Areas
Markers: ⭐ ⚠️ · Confidence: 🔴 · Last reviewed: —
TL;DR¶
When several route templates could match a URL, the router picks the most specific one — and "specific" follows a defined order, not registration order.
- Literal text beats a constrained parameter, which beats a plain parameter, which beats a catch-all.
- Comparison happens segment by segment, left to right. The first difference decides it.
- If two candidates are genuinely equal, you get an
AmbiguousMatchException— at request time, not startup.
Definitions¶
| Term | What it is | What it means |
|---|---|---|
| Endpoint selection | a process | Choosing one endpoint when several templates match a URL. |
| Precedence | the ordering rule | How the router decides which candidate is more specific. |
| Candidate set | the matching endpoints | Every endpoint whose template matches, before selection narrows it. |
| Segment precedence | the comparison method | Compare segment by segment, left to right; first difference wins. |
AmbiguousMatchException |
an exception | Two endpoints matched equally well. Thrown per request. |
[HttpGet] etc. |
method metadata | Filters the candidate set before precedence is considered. |
Order |
a property on [Route] |
Manual override. Lower runs first. A last resort. |
MapFallback |
a method | An endpoint that matches only when nothing else does. |
RequireHost |
a method | Constrains an endpoint to a hostname, narrowing the candidate set. |
The concept¶
The problem¶
Given these three templates:
[HttpGet("orders/featured")] // A — literal
[HttpGet("orders/{id:guid}")] // B — constrained parameter
[HttpGet("orders/{slug}")] // C — plain parameter
A request for /orders/featured matches all three. featured is literal text, it is not a
GUID so B is out — but A and C both match.
Something has to choose, and it is not the order you registered them in.
The rule¶
More specific wins. Compared segment by segment, left to right.
Within one segment, specificity runs:
1. Literal text orders/featured
2. Constrained parameter orders/{id:guid}
3. Plain parameter orders/{slug}
4. Catch-all orders/{*rest}
So /orders/featured goes to A, because a literal beats a parameter in that position.
A picture: postal sorting. A letter addressed to "10 Downing Street, London" goes to the specific building, not into the general "London" pile — even though both are correct descriptions. The most precise match wins.
⚠️ This is the opposite of middleware, where registration order is everything (5.2). Route selection ignores registration order entirely for attribute routes, which surprises people who assume the two work the same way.
How it works¶
The simple version — worked examples¶
[HttpGet("orders/featured")] // A
[HttpGet("orders/{id:guid}")] // B
[HttpGet("orders/{slug}")] // C
[HttpGet("orders/{*rest}")] // D
| Request | Matches | Winner | Why |
|---|---|---|---|
/orders/featured |
A, C, D | A | Literal beats parameter |
/orders/7f9a... (a GUID) |
B, C, D | B | Constrained beats unconstrained |
/orders/blue-widget |
C, D | C | Parameter beats catch-all |
/orders/a/b/c |
D | D | Only the catch-all matches multiple segments |
Segment by segment, left to right¶
Specificity is compared one segment at a time, and the first difference decides — later segments are not consulted.
[HttpGet("{category}/products/{id}")] // A — parameter, literal, parameter
[HttpGet("shop/{controller}/{id}")] // B — literal, parameter, parameter
For /shop/products/5:
| Segment | A | B | Result |
|---|---|---|---|
| 1 | {category} — parameter |
shop — literal |
B wins here |
| 2 | (not compared) |
B wins on the first segment, and it does not matter that A is more specific in segment two. That left-to-right rule is the part people get wrong when reasoning about which route will match.
⚠️ HTTP method filters first¶
Before precedence is considered, candidates are filtered by HTTP method:
Those never compete — a GET request only ever considers the first. So identical templates with
different methods are fine and normal.
⚠️ If a template matches but no candidate accepts the method, you get 405 Method Not Allowed, not 404. That is correct behaviour and occasionally confusing when debugging — the URL exists, the verb does not.
How it actually works — ambiguity¶
When two candidates are genuinely equal, the router cannot choose:
[HttpGet("orders/{id}")]
public IActionResult GetById(string id) { }
[HttpGet("orders/{code}")] // ⚠️ same shape, same method
public IActionResult GetByCode(string code) { }
AmbiguousMatchException: The request matched multiple endpoints.
⚠️ This throws at request time, not at startup. The application starts happily, and the first request to that URL produces a 500. So an ambiguity introduced by a change may not be noticed until someone hits that specific path.
Three ways to resolve it, in order of preference:
1. Make one more specific — the right fix:
[HttpGet("orders/{id:guid}")] // constrained
[HttpGet("orders/code/{code}")] // extra literal segment
2. Use Order — a manual override, and a last resort:
[HttpGet("orders/{id}", Order = 1)]
[HttpGet("orders/{code}", Order = 2)] // lower runs first, so this loses
⚠️ Order overrides the natural precedence, which makes routing harder to reason about — you
can no longer predict behaviour from the templates alone. Reach for it only when you cannot change
the templates.
3. Reconsider the design. Two actions competing for the same URL shape usually means the API
is ambiguous to callers too. If a human cannot tell whether /orders/abc is an ID or a code,
neither can the router.
Fallback endpoints¶
MapFallback registers something that matches only when nothing else does:
app.MapControllers();
// Single-page app: unmatched paths return index.html so client-side routing works
app.MapFallbackToFile("index.html");
// Or a custom handler
app.MapFallback(() => Results.NotFound(new ProblemDetails
{
Status = StatusCodes.Status404NotFound,
Title = "No matching endpoint"
}));
A fallback has the lowest possible precedence, below even a catch-all — so it never competes with a real endpoint.
⚠️ MapFallbackToFile in an API is a trap. It means a typo'd API URL returns HTML with a 200
status instead of a JSON 404, and clients then try to parse an HTML page. If you serve both an SPA
and an API, scope the fallback so it does not swallow /api:
The deeper detail — conventional routes are different¶
⚠️ Conventional routes ARE evaluated in registration order (8.3):
app.MapControllerRoute("blog", "blog/{year:int}/{slug}", new { controller = "Blog", action = "Post" });
app.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
The first pattern to match wins, so specific patterns must be registered first. Putting
default first means nothing after it ever matches, because it matches almost everything.
So the two systems behave oppositely:
| Selection rule | |
|---|---|
| Attribute routes | Most specific wins. Registration order irrelevant. |
| Conventional routes | First registered that matches wins. |
That inconsistency is worth remembering, because it is a genuine source of confusion in applications using both.
Attribute routes are also considered before conventional ones, so an attribute-routed action wins over a conventional pattern that would also match.
Code¶
Resolving a real ambiguity:
// ✗ BEFORE — throws AmbiguousMatchException on /products/anything
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet("{id}")]
public IActionResult GetById(int id) { }
[HttpGet("{sku}")]
public IActionResult GetBySku(string sku) { }
}
// ✓ AFTER — constraints make the templates distinguishable
[ApiController]
[Route("api/[controller]")]
public class ProductsController(IProductService products) : ControllerBase
{
// Literal — highest precedence, so it wins over both below
[HttpGet("featured")]
public async Task<IActionResult> Featured(CancellationToken ct)
=> Ok(await products.GetFeaturedAsync(ct));
// Constrained — beats the plain parameter
[HttpGet("{id:int:min(1)}")]
public async Task<IActionResult> GetById(int id, CancellationToken ct)
=> await products.GetAsync(id, ct) is { } p ? Ok(p) : NotFound();
// Custom constraint — also beats a plain parameter
[HttpGet("{sku:sku}")] // see 8.5
public async Task<IActionResult> GetBySku(string sku, CancellationToken ct)
=> await products.GetBySkuAsync(sku, ct) is { } p ? Ok(p) : NotFound();
// Plain parameter — the fallback for anything else
[HttpGet("{slug:minlength(3)}")]
public async Task<IActionResult> GetBySlug(string slug, CancellationToken ct)
=> await products.GetBySlugAsync(slug, ct) is { } p ? Ok(p) : NotFound();
}
Requests resolve predictably:
/api/products/featured → Featured (literal)
/api/products/42 → GetById (:int matches)
/api/products/ABC1234 → GetBySku (:sku matches)
/api/products/blue-widget → GetBySlug (only the plain parameter is left)
⚠️ The two constrained routes must not overlap. If a SKU could also be all digits, /products/1234
would match both :int and :sku equally and throw. Making the constraints mutually exclusive is
part of the design, not an afterthought.
Debugging a selection problem¶
if (app.Environment.IsDevelopment())
{
app.MapGet("/debug/routes", (IEnumerable<EndpointDataSource> sources) =>
sources.SelectMany(s => s.Endpoints)
.OfType<RouteEndpoint>()
.OrderBy(e => e.RoutePattern.RawText)
.Select(e => new
{
Pattern = e.RoutePattern.RawText,
Order = e.Order,
Methods = e.Metadata.GetMetadata<HttpMethodMetadata>()?.HttpMethods
}));
}
Seeing every registered pattern in one list is usually enough to spot the overlap (8.1). Development only — it publishes your whole API surface.
Interview questions¶
Q: If two routes could match a URL, how does ASP.NET Core choose?
By specificity, not registration order. Templates are compared segment by segment from left to
right, and within a segment a literal beats a constrained parameter, which beats a plain
parameter, which beats a catch-all. The first segment where they differ decides it — later
segments are not consulted. So orders/featured wins over orders/{slug} for the URL
/orders/featured, regardless of which was registered first.
Q: What happens when two routes are equally specific?
You get an AmbiguousMatchException. The important detail is that it is thrown per request,
not at startup, so the application starts fine and the first call to that URL returns a 500. That
means an ambiguity introduced by a change might not surface until someone hits that particular
path. The right fix is to make one route more specific with a constraint or an extra literal
segment; there is an Order property as a manual override, but it defeats the natural precedence
and makes routing harder to reason about.
Q: Do conventional routes work the same way?
No, and that inconsistency catches people out. Conventional routes registered with
MapControllerRoute are evaluated in registration order — the first pattern that matches
wins — so the general {controller}/{action}/{id?} pattern must be registered last or nothing
after it is ever reached. Attribute routes ignore registration order entirely and use specificity.
Attribute routes are also considered ahead of conventional ones.
Q: What is a fallback endpoint?
One registered with MapFallback that matches only when nothing else does — it has lower
precedence than any real endpoint, including a catch-all. The common use is a single-page app,
where MapFallbackToFile("index.html") lets client-side routing handle unknown paths. The trap
is using it in an application that also serves an API: a mistyped API URL then returns HTML with
a 200 status instead of a JSON 404, and the client tries to parse a web page. Scoping the fallback
so it does not swallow the API paths avoids that.
Traps ⚠️¶
AmbiguousMatchExceptionthrows per request, not at startup. The app starts fine and fails on one URL.- Attribute routes ignore registration order; conventional routes depend on it. Opposite rules in the same framework.
- Precedence is decided at the first differing segment. Later segments do not count.
Orderoverrides natural precedence and makes routing unpredictable. Last resort.- A matching template with the wrong HTTP method gives 405, not 404.
MapFallbackToFilein an API returns HTML for mistyped API URLs, with a 200 status.- Two constraints that can both match the same value are ambiguous — make them mutually exclusive.
- Adding a route can silently change which action handles an existing URL if the new one is more specific.
Related¶
- 8.1 Endpoint routing — the endpoint table
- 8.3 Conventional vs attribute routing — the two ordering rules
- 8.4 Route templates — literals, parameters and catch-alls
- 8.5 Route constraints — how constraints add specificity
- 8.10 Catch-all routes — lowest precedence
- 5.2 Middleware order — where order does matter
- 10.3 Status codes — 404 versus 405