Route ambiguity occurs when multiple ASP.NET Core routes match a request with the same score. Because neither route is more specific, routing throws an exception instead of selecting an endpoint. section 13.1.5 section 13.3.2
Route selection becomes ambiguous when:
- Two routes have equal precedence for the incoming URL. section 13.1.5
- Constraints allow the same value to satisfy multiple patterns, such as both int and double. section 13.3.2
- A URL such as /23 matches both {number:int} and {number:double}, while /23.5 matches only the double route. section 13.3.2
Prefer eliminating the overlap by making routes more specific: add literal segments or a constraint. When that is impossible, assign explicit endpoint order. The route with the lowest Order value wins among matching routes. section 13.3.2
Resolving overlapping numeric routes
Map {number:int} and {number:double}, then set their endpoint orders to 1 and 2. A request for /23 is consequently handled by the integer endpoint rather than producing an ambiguous-route exception. section 13.3.2
Listing 13.26 Defining ambiguous routes in the Program.cs file in the Platform folder
using Platform;
var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<RouteOptions>(opts => {
opts.ConstraintMap.Add("countryName",
typeof(CountryRouteConstraint));
});
var app = builder.Build();
app.Map("{number:int}", async context => {
await context.Response.WriteAsync("Routed to the int endpoint");
});
app.Map("{number:double}", async context => {
await context.Response
.WriteAsync("Routed to the double endpoint");
});
app.MapFallback(async context => {
await context.Response.WriteAsync("Routed to fallback endpoint");
});
app.Run();
Inspect the runnable Program.cs configuration that creates overlapping integer and double routes before applying explicit ordering. section 13.3.2
