skip to content

Two ASP.NET Core 10 endpoints both handle GET /orders/{id} and requests fail with AmbiguousMatchException; how do precedence and Order decide, and how do you fix it?

level: seniorimportance: should knowfreq 40%

answer

  1. Order first, then template precedence
  2. literal > constrained > parameter > catch-all
  3. lower Order wins, default 0
  4. thrown per request, not at startup
  5. message lists endpoint display names

basics

~20 s

Routing ranks candidates by Order, then template precedence; two valid candidates tied on both throw AmbiguousMatchException at request time, naming both endpoints. Remove the duplicate, make the templates differ, or give one a lower Order with WithOrder.

solid answer

~40 s

Endpoint routing ranks every candidate that survives matching by `Order` first, where lower wins and the default is 0, then by route-template precedence, then by policy comparers such as HTTP method and host metadata. Precedence scores each segment: a literal beats a constrained parameter, which beats a plain parameter, which beats a catch-all. Two endpoints for `GET /orders/{id}`, say a controller action and a Minimal API added during a migration, tie on everything, so the selector throws `AmbiguousMatchException` with "The request matched multiple endpoints" and their display names. Because constraints can make templates disjoint, this cannot be detected at startup; it fails per request. Delete the duplicate, make the templates differ with a literal or constraint, or, as a last resort, set `.WithOrder(-1)` or `[HttpGet("orders/{id}", Order = -1)]` on the endpoint that should win.

code

csharp · 12 lines
csharp
var app = WebApplication.CreateBuilder(args).Build();

// Precedence decides, no Order needed:
app.MapGet("/orders/pending", () => "pending orders");               // literal wins
app.MapGet("/orders/{id:int}", (int id) => $"order {id}");          // then constrained
app.MapGet("/orders/{reference}", (string r) => $"order ref {r}"); // then plain

// Two templates that tie: Order breaks the tie (lower wins)
app.MapGet("/couriers/{id}", (string id) => "v2 courier").WithOrder(-1);
app.MapGet("/couriers/{courierId}", (string courierId) => "legacy courier");

app.Run();

go deeper

for a junior

Recall that a literal segment beats a parameter, and that two identical routes make requests fail with an ambiguous-match error.

for a middle

Explain the precedence ranks, that Order is compared first with lower values winning, and why registration order does not matter.

for a senior

Diagnose an AmbiguousMatchException from its display names, explain why it is request-time only, and fix it by removing duplicates or changing templates before using WithOrder.

for a principal

Prevent collisions structurally: route ownership per team or module and a test that enumerates endpoints, rather than Order values sprinkled to break ties.

## How routing ranks candidates After the routing middleware has collected every endpoint whose template matches the path and removed those whose constraints or matcher policies reject the request, the **endpoint selector** picks the winner. In the v10.0.12 source, candidates are compared in this order: 1. **`RouteEndpoint.Order`**: lower values win; Minimal API and attribute-routed endpoints default to `0`; `MapControllerRoute` assigns increasing orders in call order; `MapFallback` uses `int.MaxValue`. 2. **Route template precedence**: how specific the template is. 3. **Policy comparers**: an endpoint with HTTP-method metadata beats one without, and one with host metadata beats one without. If the best valid candidate ties with another on all of these, the selector throws. ## Route template precedence Precedence is computed per segment, left to right, from these ranks: | Segment kind | Example | Rank | |---|---|---| | Literal | `orders` | 1 (most specific) | | Constrained parameter or complex segment | `{id:int}`, `{name}.{ext}` | 2 | | Plain parameter | `{id}` | 3 | | Constrained catch-all | `{**path:nonfile}` | 4 | | Plain catch-all | `{**path}` | 5 (least specific) | So `/orders/pending` beats `/orders/{id:int}`, which beats `/orders/{id}`, which beats `/orders/{**rest}`. Registration order does **not** matter for these endpoints. ## Where the ambiguity comes from In a food-delivery API being migrated from controllers to Minimal APIs, both of these end up in the app: ```csharp [ApiController, Route("orders")] public class OrdersController : ControllerBase { [HttpGet("{id}")] public IActionResult Get(string id) => Ok(id); } app.MapGet("/orders/{id}", (string id) => Results.Ok(id)); ``` Same order (0), same precedence, both GET. `GET /orders/42` fails with an `AmbiguousMatchException` whose message reads "The request matched multiple endpoints. Matches:" followed by the display names, for example `FoodDelivery.OrdersController.Get (FoodDelivery)` and `HTTP: GET /orders/{id}`. Points worth knowing: - The exception type is internal to `Microsoft.AspNetCore.Routing.Matching`; it is not `System.Reflection.AmbiguousMatchException`, and you cannot catch it by type in your own code. Exception-handling middleware sees it like any unhandled error, usually a 500. - It is thrown **per request**, not at startup. The docs explain why: `/{message:alpha}` and `/{message:int}` have the same precedence but never match the same URL, so a startup check would reject valid apps. - Parameter **names** do not matter: `/orders/{id}` and `/orders/{orderId}` are just as ambiguous. ## Fixing it In order of preference: 1. **Remove the duplicate.** During a migration, delete the old controller action when the Minimal API goes in. 2. **Make the templates differ** with a literal (`/orders/by-ref/{reference}`) or a constraint (`/orders/{id:int}` beside `/orders/{reference}`), so precedence decides. 3. **Set an order** on the endpoint that should win: `.WithOrder(-1)` on a Minimal API, `Order = -1` on `[HttpGet]` or `[Route]` for an action. The docs recommend `Order` "only when necessary to avoid an ambiguity", because it hides the overlap instead of removing it. ## Order on controllers Controllers set the same `RouteEndpoint.Order` through their attributes: `[HttpGet("{id}", Order = -1)]` on an action or `[Route("orders", Order = -1)]` on a route template. Conventional routes get their order from the sequence of `MapControllerRoute` calls, which is why the docs advise listing area routes before the default route and greedy catch-all routes last. Mixing conventional and attribute routes is legal, but collisions between them are reported the same way, as an ambiguity on the first request that hits both. ## Finding collisions before users do - Read the display names in the exception; give Minimal API endpoints `WithDisplayName` or named handler methods so they are recognisable. - Enumerate endpoints at startup in a test by resolving `EndpointDataSource` from DI and grouping `RouteEndpoint.RoutePattern.RawText` together with the HTTP methods. - Hit each route once in an integration test; ambiguity only shows up on a real request. ## What interviewers listen for - The ranking: Order, then precedence, then policy metadata. - Literal over constrained over plain parameter over catch-all. - The exception is a request-time failure listing display names. - `WithOrder` as a last resort, not the first fix.

  • Why can't ASP.NET Core detect ambiguous routes at startup?
    Because two templates with identical precedence may never match the same URL once constraints and matcher policies run. The routing docs use `/{message:alpha}` and `/{message:int}`: same precedence, disjoint values. A startup error would reject such valid apps, so ambiguity is reported only when a real request finds two equally ranked valid candidates.
  • Does registration order decide between two Minimal API endpoints with the same template?
    No. Endpoint routing processes all endpoints at once and ranks them by Order and precedence; the order of `MapGet` calls is irrelevant. The one exception is `MapControllerRoute` and `MapAreaControllerRoute`, which assign increasing Order values in the sequence you call them, to keep conventional routing's historical behaviour.
  • Can you catch the routing AmbiguousMatchException in a try/catch around app code?
    Not by type: it is an internal class in `Microsoft.AspNetCore.Routing.Matching`, unrelated to `System.Reflection.AmbiguousMatchException`. It is thrown inside the routing middleware, so exception-handling middleware placed before routing sees it as an unhandled exception, typically turning it into a 500. The real fix is removing the tie.

  • Says the endpoint registered first wins when two Minimal API templates tie.
  • Believes a higher Order value gives an endpoint higher priority.
  • Expects ASP.NET Core to report route ambiguities when the app starts.
  • Thinks renaming {id} to {orderId} in one template removes the ambiguity.
  • Catches System.Reflection.AmbiguousMatchException to handle routing collisions.
  • Reaches for WithOrder before removing the duplicate endpoint.