Endpoint routing in ASP.NET Core: route templates, parameters, constraints and catch-alls, the matcher and route precedence rules, ambiguous matches, link generation with LinkGenerator and named routes, and endpoint metadata consumed by authorisation, CORS, rate limiting and OpenAPI.
Endpoint routing splits routing into two steps: UseRouting matches the request's path and HTTP method to one endpoint and stores it on HttpContext, and the endpoint middleware at the end executes it. Anything between them, like authorisation, CORS and rate limiting, reads the endpoint's metadata. Routes are defined by templates (/orders/{id:int}, optional and default values, catch-alls {**path}) with constraints that narrow matches. When several routes match, precedence picks the most specific: literals beat parameters, constrained beats unconstrained, catch-alls lose; a true tie throws AmbiguousMatchException. Link generation (LinkGenerator, CreatedAtRoute) builds URLs from route names and values so URLs aren't hard-coded. The trade-off: constraints help disambiguate but are not validation; a failed constraint is a 404, not a 400.
"Endpoint routing, which has been the model since ASP.NET Core 3.0, splits routing into matching and execution.
UseRoutingtakes the method and path, runs them through a single matcher built from every endpoint in the app, Minimal APIs, controllers, Razor Pages, SignalR hubs, gRPC services, and picks one. It sets that endpoint and the route values onHttpContext. The endpoint middleware at the end of the pipeline runs it. The reason for the split is that middleware in between can make decisions based on the selected endpoint: authorisation reads[Authorize], CORS reads the policy name, the rate limiter reads its policy, and output caching reads its settings.Templates are literals and parameters:
/orders/{id:int}, an optional{page?}, a default{format=json}and a catch-all{**path}. Constraints likeint,guid,minlengthorregexnarrow what matches. When more than one route matches, precedence decides: a literal segment beats a parameter, a constrained parameter beats an unconstrained one, and a catch-all loses to anything more specific. If two routes are equally specific you get anAmbiguousMatchExceptionat request time, not at start-up. For URLs I never concatenate strings; I name the route withWithNameand useLinkGeneratororCreatedAtRoute, so a template change updates every link.The mistake I see is using constraints as validation:
{age:range(18,120)}turns a bad input into a 404 instead of a useful 400. Constraints are for choosing between routes; validation belongs in the handler or a filter."
| Syntax | Meaning | Example |
|---|---|---|
{id} |
Required parameter | /orders/{id} |
{id:int} |
Constrained parameter | /orders/42 matches, /orders/abc does not |
{page?} |
Optional | /products/{page?} |
{format=json} |
Default value | /export/{format=json} |
{*path} / {**path} |
Catch-all (** keeps / unencoded in generated links) |
/files/{**path} |
| Route | Rank for /orders/new |
|---|---|
/orders/new (literal) |
1st |
/orders/{id:int} |
does not match (new isn't an int) |
/orders/{slug} |
2nd |
/orders/{**rest} |
3rd |
| Metadata | Read by |
|---|---|
RequireAuthorization, [Authorize], AllowAnonymous |
Authorisation middleware |
RequireCors |
CORS middleware |
RequireRateLimiting |
Rate limiter |
CacheOutput |
Output caching |
WithName, WithTags, Produces |
Link generation, OpenAPI |
In a catalogue API with about 300 endpoints, the matcher resolves a route in well under a microsecond regardless of count, because it is a compiled DFA, not a list scanned in order. A real incident came from two controllers both defining GET api/products/{id} after a refactor; it surfaced as 500s with AmbiguousMatchException only for that path, and an endpoint-listing test now fails the build on duplicate templates.
Checks that the candidate understands how a URL becomes an endpoint and why that matters for the rest of the pipeline.
Green flags
AmbiguousMatchException.LinkGenerator/named routes rather than string URLs.Red flags
Every Map* call and every MapControllers/MapRazorPages adds endpoints to an EndpointDataSource. At start-up (and lazily on first request) the DfaMatcherBuilder compiles all templates into a deterministic finite automaton keyed on path segments, with policies for HTTP method, host and content type applied as extra node policies.
┌─ "orders" ─┬─ "new" ─► GET /orders/new
root ── "api" ─┤ ├─ {id:int} ─► GET /orders/{id:int}
│ └─ {**rest} ─► GET /orders/{**rest}
└─ "products" ─ {id} ─► GET /products/{id}
Matching is roughly proportional to the number of path segments, not the number of routes.
The DFA yields a candidate set. The matcher then:
int, guid, alpha, regex, custom IRouteConstraint).Accepts content type.AmbiguousMatchException.Matched parameters are stored in HttpContext.Request.RouteValues. Minimal APIs and MVC bind them to handler parameters by name. Values are URL-decoded, except / in a {**path} catch-all.
LinkGenerator (a singleton) works from endpoint names or route values. It takes "ambient" values from the current request, fills in the template, applies defaults and constraints and returns null if the values cannot satisfy any endpoint, which is a common silent failure. CreatedAtRoute("GetOrder", new { id }) uses the same machinery to build the Location header.
Each endpoint carries an EndpointMetadataCollection: attributes from controllers and actions, plus anything added with .WithMetadata() or the convenience methods. Middleware read it with context.GetEndpoint()?.Metadata.GetMetadata<T>(). This is how you build your own endpoint-aware middleware without filters.
CreateSlimBuilder excludes regex constraints by default to save size for Native AOT.MapGroup) add a shared prefix and shared metadata to many endpoints..ShortCircuit() (.NET 8+) makes the endpoint run immediately after routing, skipping later middleware, useful for robots.txt or health endpoints./orders/new, /orders/{id:int} and /orders/{slug} and call /orders/new, /orders/5 and /orders/abc.AmbiguousMatchException on request.EndpointDataSource into an endpoint and list every route pattern and its metadata.LinkGenerator.GetPathByName with a missing route value and observe the null result.TestServer.Templates, constraints, names, link generation and reading metadata in middleware.
// Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseRouting();
// Endpoint-aware middleware: reads metadata of the endpoint chosen by UseRouting
app.Use(async (context, next) =>
{
if (context.GetEndpoint()?.Metadata.GetMetadata<AuditAttribute>() is { } audit)
app.Logger.LogInformation("Audited action {Action}", audit.Action);
await next(context);
});
app.UseAuthorization();
var orders = app.MapGroup("/orders").WithTags("Orders");
orders.MapGet("/new", () => "order form"); // literal wins over {slug}
orders.MapGet("/{id:int}", (int id) => TypedResults.Ok(new Order(id)))
.WithName("GetOrder"); // name used for links
orders.MapGet("/{slug}", (string slug) => $"order by slug {slug}"); // fallback for non-int
orders.MapPost("/", (CreateOrder cmd, LinkGenerator links, HttpContext http) =>
{
var order = new Order(Random.Shared.Next(1, 10_000));
// Never hand-build URLs: the template can change without breaking clients' Location header
var url = links.GetUriByName(http, "GetOrder", new { id = order.Id });
return TypedResults.Created(url, order);
}).WithMetadata(new AuditAttribute("CreateOrder"));
app.Run();
public sealed record Order(int Id);
public sealed record CreateOrder(string Sku, int Quantity);
[AttributeUsage(AttributeTargets.Method)]
public sealed class AuditAttribute(string action) : Attribute { public string Action { get; } = action; }
LinkGenerator or CreatedAtRoute.WithName or [HttpGet(Name = ...)]. Why it is wrong: Endpoint names must be unique; duplicates throw when link generation (or the OpenAPI document) is built. Instead: Use a naming convention such as Feature.Action and add a test that enumerates endpoint names.CreateSlimBuilder for Native AOT. Instead: Prefer built-in constraints (int, guid, alpha, length) or literal segments; measure with BenchmarkDotNet if routing shows up in a profile.Map calls. Instead: Rely on specificity, or set an explicit order if you must.null from LinkGenerator. Why it is wrong: It means the values couldn't match the route, and you return a broken Location header. Instead: Treat null as a bug and test link generation.UseRouting. Why it is wrong: GetEndpoint() returns null there. Instead: Put it after UseRouting.{*path} when generating links with slashes. Why it is wrong: Single-star catch-alls encode / as %2F in generated URLs. Instead: Use {**path}.The design idea worth naming is that routing is the point where the framework learns what the request is for, and everything after it can make endpoint-specific decisions without filters. That is why authorisation, CORS, rate limiting and output caching are all metadata-driven in modern ASP.NET Core. A senior uses that: custom concerns become metadata plus a small middleware, and route groups apply them consistently to whole features.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Route constraint | Two routes differ only by parameter type | Failed match is a 404 | Validating business rules |
| Explicit order | Rare unavoidable overlaps | Hidden, surprising behaviour | Normal routing design |
| Route groups with shared metadata | Feature-wide auth, tags, rate limits | Indirection when reading one endpoint | A handful of endpoints |
| Custom endpoint metadata + middleware | Cross-cutting, endpoint-specific policy | Small amount of code | When a built-in feature already exists |
ASP.NET Core is Microsoft's cross-platform web framework for .NET 10: your app is a normal console process that hosts its own web server. A request arrives at Kestrel, which parses the HTTP bytes and builds an HttpContext. That context is passed through the middleware pipeline, an ordered chain of RequestDelegates registered in Program.cs. Along the way UseRouting matches the URL to an endpoint (a Minimal API handler, controller action or Razor Page), later middleware such as authentication and authorisation uses that endpoint's metadata, and finally the endpoint runs and writes the response. The response then unwinds back through the middleware in reverse. The key trade-off: the pipeline is tiny and fast because you only add what you need, but order is behaviour, so a wrongly ordered Use... call silently changes what happens.
Chain of Responsibility sends a request along a chain of handlers; each one decides whether to handle it, pass it on, or both, and the sender doesn't know which one acted.
next. ASP.NET Core middleware (RequestDelegate next) and DelegatingHandler in HttpClient work this way.Short-circuiting means returning without calling next: authentication returning 401, static files serving a file, a cache hit. That's why order matters: exception handling must wrap everything, and authentication must run before authorisation.
The trade-off is decoupling and composability against long implicit chains whose order lives far from the handlers.
Last updated 23 Nov 2026.