⚙️ Fix a Minimal API Request That Matches the Wrong Handler Because Two Routes Differ Only by a Trailing Optional Parameter
ASP.NET Core’s routing engine picks the best match among all registered routes for a given request path, and when two minimal API routes differ only by a trailing optional segment, a request that could satisfy either one doesn’t always resolve to the route you’d intuitively expect – the more specific route should win by routing’s own precedence rules, but a subtly different parameter constraint or ordering of app.MapGet calls can flip which handler actually executes, with no routing conflict error raised at startup to warn you.
🔎 The Problem
app.MapGet("/orders/{id}", (int id) =>
Results.Ok($"single order {id}"));
app.MapGet("/orders/{id?}", (int? id) =>
Results.Ok(id is null ? "all orders" : $"order {id}"));
// GET /orders/42
// Expected: the first, more specific handler.
// Actual: depends on registration order and exact route
// template matching rules - the optional-parameter route
// can end up matching requests the required-parameter
// route was clearly meant to own, with no startup error
// indicating the two routes overlap at all.
✅ Fix: Make Route Specificity Explicit Instead of Relying on Registration Order
- Avoid registering a required-parameter route and an optional-parameter version of the same path together – collapse them into one handler that treats the parameter as nullable internally, which removes the ambiguity entirely instead of relying on routing precedence to resolve it correctly.
- If two similar routes genuinely need to stay separate, give them distinct path segments (/orders/{id} versus /orders/search) rather than letting an optional trailing parameter be the only thing that tells them apart.
- Log the actual matched endpoint for a request during testing (app.Use middleware that reads HttpContext.GetEndpoint()) to directly confirm which handler is executing, rather than inferring it only from the response body – two handlers that both happen to return similar-looking JSON can mask a routing mismatch for a long time.
🚨 Why This Is Dangerous
- Because no startup-time error flags this kind of overlapping route pair, the wrong handler can run silently in production for a specific path shape that testing happened not to exercise, and it surfaces only when a particular ID value or request pattern finally triggers the ambiguous case.
Two routes that look unambiguous to you can still look ambiguous to the router – and the router, not your intent, is what decides which handler actually runs.

