⚙️ Asp.Net Core: Fix a Minimal API Route Matching the Wrong Overload
Minimal API routing generally favors a literal path segment over a parameterized one, but that preference only kicks in reliably when the parameterized segment carries an explicit route constraint — a bare {id} with no type constraint can, depending on registration order and how routes are split across MapGroup calls, end up treated as equally specific to a literal sibling segment, so /orders/latest can be silently routed into the handler meant for /orders/{id}, receiving the literal string "latest" as the id instead of ever reaching its own handler.
🔎 The Problem
app.MapGet("/orders/{id}", (string id) =>
{
// receives id = "latest" instead of "/orders/latest" ever
// reaching the handler below, because {id} has no constraint
return LookupOrderById(id);
});
app.MapGet("/orders/latest", () => GetMostRecentOrder());
// registered AFTER the parameterized route above - and without a
// constraint on {id}, routing does not reliably prefer this literal
// segment over the earlier parameterized one in every scenario
✅ Fix: Constrain the Parameter, Don’t Rely on Registration Order
- Add an explicit route constraint to the parameterized segment (
{id:int},{id:guid}) whenever a literal sibling route could otherwise collide with it — a constrained parameter route simply can’t match a literal string like"latest"in the first place. - Register more specific literal routes before parameterized ones explicitly, as a second line of defense, rather than assuming ASP.NET Core’s specificity rules alone will always resolve the collision the way you expect across every grouping and ordering combination.
- Add an integration test that specifically hits the literal route (
/orders/latest) and asserts which handler responded — a routing collision like this compiles perfectly cleanly and only shows up as a wrong response body at runtime.
🚨 Why This Is Dangerous
- Returning a 200 OK with order id “latest” silently resolved by the parameterized handler’s own database lookup logic — which might legitimately return null, or worse, a coincidentally matching record — instead of a clear 404 or the actually intended ‘most recent order’ response.
An unconstrained route parameter doesn’t just accept anything — it can quietly outcompete the literal route you meant to hit.
