📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How does endpoint routing work in ASP.NET Core? Explain route templates and constraints, how the router chooses between matching routes (precedence), how link generation works, and what endpoint metadata is used for.

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.

Intermediate Theory Intermediate aspnet-core endpoint-metadata endpoint-routing linkgenerator route-constraints routing

🎯 Key points

  • Endpoint routing separates matching (UseRouting) from execution (endpoint middleware), so middleware in between can read the selected endpoint
  • Route templates: literals, {param}, optional {param?}, defaults {param=value}, catch-all {**path}
  • Constraints such as {id:int}, {slug:regex(...)}, {date:datetime} narrow matches; they are for disambiguation, not input validation, and regex constraints are the slowest
  • Precedence: more literal segments win over parameters, constrained parameters over unconstrained, and catch-alls lose; ties raise AmbiguousMatchException
  • Order can be overridden with an explicit order (Order property in MVC attributes, WithOrder in Minimal APIs)
  • LinkGenerator / CreatedAtRoute generate URLs from unique route names and values, so URLs are never hand-built
  • Route groups (MapGroup) share a prefix and metadata such as auth, tags and rate limits across a feature
  • Endpoint metadata (Authorize, CORS policy, rate limit policy, tags, Produces) is read by middleware and OpenAPI

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"Endpoint routing, which has been the model since ASP.NET Core 3.0, splits routing into matching and execution. UseRouting takes 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 on HttpContext. 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 like int, guid, minlength or regex narrow 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 an AmbiguousMatchException at request time, not at start-up. For URLs I never concatenate strings; I name the route with WithName and use LinkGenerator or CreatedAtRoute, 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."


Template syntax

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}

Precedence (most specific wins)

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

What metadata drives

Metadata Read by
RequireAuthorization, [Authorize], AllowAnonymous Authorisation middleware
RequireCors CORS middleware
RequireRateLimiting Rate limiter
CacheOutput Output caching
WithName, WithTags, Produces Link generation, OpenAPI

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate understands how a URL becomes an endpoint and why that matters for the rest of the pipeline.

Green flags

  • Explains the matching/execution split and why auth must follow routing.
  • Knows precedence rules and AmbiguousMatchException.
  • Uses LinkGenerator/named routes rather than string URLs.
  • Knows constraints produce 404s, not 400s.

Red flags

  • Thinks routes are tried in registration order.
  • Uses constraints for validation.
  • Has never heard of endpoint metadata.

📚 Learn in depth

1. One route table for everything

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.

2. Candidates, constraints and precedence

The DFA yields a candidate set. The matcher then:

  1. Evaluates constraints (int, guid, alpha, regex, custom IRouteConstraint).
  2. Applies endpoint selector policies: HTTP method (405 if the path matches but not the method), host, Accepts content type.
  3. Sorts remaining candidates by order, then route precedence: computed per segment (literal > constrained parameter > parameter > catch-all, and complex segments in between).
  4. If more than one remains with equal score, throws AmbiguousMatchException.

3. Route values and binding

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.

4. Link generation

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.

5. Metadata

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.

6. Costs and variations

  • Regex constraints are compiled but still the slowest; CreateSlimBuilder excludes regex constraints by default to save size for Native AOT.
  • Route groups (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.

Try it yourself

  1. Map /orders/new, /orders/{id:int} and /orders/{slug} and call /orders/new, /orders/5 and /orders/abc.
  2. Map two identical templates and observe the AmbiguousMatchException on request.
  3. Inject EndpointDataSource into an endpoint and list every route pattern and its metadata.
  4. Use LinkGenerator.GetPathByName with a missing route value and observe the null result.
  5. Benchmark matching with 10 vs 1,000 routes using BenchmarkDotNet and TestServer.

💻 Code

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; }

⚠ Common mistakes

  • Mistake: Using route constraints for validation. Why it is wrong: A failed constraint means 'no route', so the client gets a 404 instead of a 400 explaining the problem. Instead: Use constraints only to disambiguate; validate in the handler or a filter.
  • Mistake: Building URLs with string concatenation. Why it is wrong: Template changes, path bases and encoding break links silently. Instead: Name routes and use LinkGenerator or CreatedAtRoute.
  • Mistake: Giving two endpoints the same name with 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.
  • Mistake: Heavy use of regex constraints and complex segments on hot routes. Why it is wrong: Regex evaluation is the slowest constraint, adds start-up cost, and is excluded by 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.
  • Mistake: Assuming routes are matched in registration order. Why it is wrong: Endpoint routing uses precedence, not order of Map calls. Instead: Rely on specificity, or set an explicit order if you must.
  • Mistake: Ignoring a 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.
  • Mistake: Placing endpoint-aware middleware before UseRouting. Why it is wrong: GetEndpoint() returns null there. Instead: Put it after UseRouting.
  • Mistake: Using {*path} when generating links with slashes. Why it is wrong: Single-star catch-alls encode / as %2F in generated URLs. Instead: Use {**path}.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions UseRouting selecting the endpoint. Why: Checks where routing sits in the end-to-end request flow.
    How to answer

    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.

  2. When: Candidate describes middleware reading endpoint metadata. Why: Checks how endpoint-aware middleware fits the wider pipeline pattern.
    How to answer

    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.

    • Classic variant: the first handler that can deal with it stops the chain, like an expense approval going team lead → manager → director by amount.
    • Pipeline variant: every handler can act before and after calling 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.

↩ Usually asked after

More in ASP.NET Core Fundamentals

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me