skip to content

Endpoint Routing Engine

How ASP.NET Core maps a URL to an endpoint: route templates and constraints, selection by precedence, method and metadata, and generating links. Interviewers ask why a request hit the wrong route.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

16

In an ASP.NET Core route template, how do a required {slug}, an optional {edition?} and a default-valued {page=1} parameter differ in what they match?

level: juniorimportance: must knowfreq 68%

answer

  1. one path segment per parameter
  2. ? = no value when absent
  3. = value always produces a value
  4. optional plus default is a parse error
  5. {controller=Home}/{action=Index}/{id?}

basics

~20 s

A required parameter such as {slug} must be present in the URL. An optional {edition?} may be missing and then produces no route value, while a default {page=1} may also be missing but always produces a value.

solid answer

~40 s

A route template is literal text plus parameters in braces. A plain `{slug}` must match a non-empty path segment, so `books/{slug}` never matches `/books`. Appending `?` makes it optional: `books/{slug}/{edition?}` matches `/books/dune` and `/books/dune/second`, and in the first case there is simply no `edition` route value. A default value, `catalog/{genre}/{page=1}`, also lets the segment be left off, but routing then fills in `page = "1"`, so a value always exists. You cannot combine the two: `{page=1?}` is rejected when the template is parsed with "An optional parameter cannot have default value." The MVC template's conventional route `{controller=Home}/{action=Index}/{id?}` uses both kinds, which is why `/` reaches `HomeController.Index` with no `id`.

code

csharp · 17 lines
csharp
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

// /books/dune         -> edition is null
// /books/dune/second  -> edition is "second"
app.MapGet("/books/{slug}/{edition?}", (string slug, string? edition) =>
    $"{slug} ({edition ?? "latest"})");

// /catalog/sci-fi     -> page is 1 (from the default)
// /catalog/sci-fi/4   -> page is 4
app.MapGet("/catalog/{genre}/{page=1}", (string genre, int page) =>
    $"{genre}, page {page}");

// app.MapGet("/catalog/{genre}/{page=1?}", ...) would throw RoutePatternException:
// "An optional parameter cannot have default value."

app.Run();

go deeper

for a junior

Recall the three forms: required {slug}, optional {edition?} and default {page=1}. Know that a default always yields a value and an optional parameter may yield none.

for a middle

Explain what the handler or action receives in each case, why /Books maps to BooksController.Index under the default route, and the parser rules such as optional-plus-default being invalid.

for a senior

Show judgement: required ids on API routes, defaults only where a fallback is meaningful, and no reserved names like page on controllers, so URL generation stays predictable as the app grows.

for a principal

Frame templates as a public contract: once bookmarked or indexed, an optional segment or default is hard to remove, so set conventions for parameter naming and optionality early.

## What a route template is In ASP.NET Core 10 every endpoint, whether it comes from `app.MapGet`, a `[Route]` attribute on a controller or `MapControllerRoute`, carries a **route template**: a string the routing middleware parses into a `RoutePattern` and compares against the request path, one segment at a time. The template has two kinds of parts: - **Literals** such as `books` or `catalog`, which must appear in the path. Literal matching is **case-insensitive** and works on the decoded path. - **Route parameters** in braces such as `{slug}`, which capture the text of a segment into a **route value** stored in `HttpContext.Request.RouteValues`. Route values captured from the URL are always **strings**; turning `"3"` into an `int` is model binding's job, not the template's. ## Required, optional and default parameters Take an online bookshop with two endpoints: ```csharp app.MapGet("/books/{slug}/{edition?}", (string slug, string? edition) => $"{slug} {edition ?? "latest"}"); app.MapGet("/catalog/{genre}/{page=1}", (string genre, int page) => $"{genre} page {page}"); ``` | Form | Example | `/books/dune` or `/catalog/sci-fi` | With the segment present | |---|---|---|---| | Required | `{slug}` | must be present, or no match | value captured | | Optional | `{edition?}` | matches; **no** route value | value captured | | Default | `{page=1}` | matches; value is `"1"` | value captured | The docs summarise the difference in two lines: a parameter with a default value **always produces a value**; an optional parameter **has a value only when the URL provides one**. That matters downstream. A handler parameter `string? edition` arrives as `null`, while `int page` arrives as `1`. In an MVC action that uses the conventional route, an omitted `{id?}` leaves an `int id` parameter at `0`, which is why the docs warn that "no entity is found in the database matching `id == 0`" if you forget to check. ## Rules the template parser enforces The parser validates a template when the endpoint is registered, so `MapGet` with a bad template throws a `RoutePatternException` at startup rather than at request time. The rules worth knowing: 1. **Optional and default cannot be combined.** `{page=1?}` fails with "An optional parameter cannot have default value." 2. **Two parameters in one segment need a literal between them.** `{controller=Home}{action=Index}` is invalid; `{name}.{ext}` is valid because the period separates them. 3. **Inside a complex segment, only a period may precede an optional parameter.** `files/{filename}.{ext?}` matches both `/files/cover.png` and `/files/cover`. 4. **A literal brace is written twice**, `{{` or `}}`, because single braces start and end a parameter. 5. **Parameter names cannot contain `{`, `}` or `/`**, and `?` may appear only at the end of a name. ## The conventional default route The MVC project template (`dotnet new mvc`) maps one conventional route in `Program.cs`: ```csharp app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); ``` It combines both kinds of parameter: - `/` matches with `controller = Home` and `action = Index` from the defaults and no `id`. - `/Books` matches `BooksController.Index`, because only `action` falls back to its default. - `/Books/Details/42` supplies all three values. The mapping depends only on the controller and action **names**, not on namespaces or method parameters. Web APIs use attribute routes instead, and `[ApiController]` requires them. ## Reserved parameter names With controllers or Razor Pages, `action`, `area`, `controller`, `handler` and `page` are **reserved route parameter names**: URL generation uses them to decide whether it is building a link to a controller action or a page. Naming a bookshop paging parameter `{page}` on an attribute-routed controller therefore causes confusing link generation; `{pageNumber}` avoids it. In an app with only Minimal APIs it matters less, but picking a neutral name everywhere is the safer habit. ## Common mistakes - Writing `{page=1?}` to get "optional with a fallback"; the default alone already makes the segment omissible. - Expecting `{slug}` to capture `fantasy/tolkien`; one parameter is one segment, and a catch-all such as `{**path}` is needed for more. - Making an id optional on an API route, so `/books` and `/books/42` hit the same handler and the handler must branch on a missing value. - Assuming `/Books` and `/books` are different routes; literal matching ignores case. ## What interviewers listen for - The precise difference: **optional means "may be absent"**, **default means "absent becomes this value"**. - That a parameter matches **one segment**; capturing several segments needs a catch-all parameter. - That route values are strings until binding converts them. - That template mistakes surface at startup as a `RoutePatternException`, not as a 404 later.

  • With the MVC template's default route, why does /Books/Details without an id still reach the action, and what does the int id parameter contain?
    In `{controller=Home}/{action=Index}/{id?}` the `id` segment is optional, so `/Books/Details` matches with controller `Books`, action `Details` and no `id` route value. Model binding then leaves `int id` at its default of `0`. The action runs and usually finds nothing for id 0, so it should check for that, or the endpoint should use an attribute route that makes `{id}` required.
  • Can a template mix a literal and two parameters in one segment, such as files/{name}.{ext?}, and what matches?
    Yes. That is a complex segment: the period separates the two parameters, and only a period may precede an optional parameter. `/files/cover.png` gives `name = cover` and `ext = png`; `/files/cover` also matches because the trailing period and extension are optional. Complex segments match their literals right to left, non-greedily, so they work best when the delimiter never appears inside the values.

  • Says {page?} and {page=1} behave the same because both make the segment optional.
  • Writes {page=1?} to get an optional parameter with a fallback value.
  • Believes a route parameter like {slug} can capture several slash-separated segments.
  • Thinks route values arrive already converted to int or Guid by the template.
  • Expects literal segments such as /Books to match case-sensitively.
open as a page

In ASP.NET Core, what do UseRouting and UseEndpoints each do, and why does middleware placed before UseRouting get null from HttpContext.GetEndpoint()?

level: middleimportance: must knowfreq 58%

basics

~10 s

UseRouting matches the request and stores the chosen endpoint on HttpContext; UseEndpoints runs that endpoint's delegate. Middleware before UseRouting runs before any endpoint has been selected, so GetEndpoint() returns null there.

open as a page

In ASP.NET Core, why does an endpoint mapped to /books/{id:int} answer 404 rather than 400 for /books/abc, and what are route constraints really for?

level: middleimportance: must knowfreq 60%

basics

~20 s

An inline constraint like :int is checked while routing matches the URL, so a failing value removes the endpoint from the candidates; with nothing selected the request ends as 404. Constraints exist to tell similar routes apart, not to validate input.

open as a page

In ASP.NET Core 10, what happens when a request's path matches a MapGet endpoint but its HTTP method, such as HEAD, does not?

level: juniorimportance: should knowfreq 42%

basics

~20 s

Routing answers 405 Method Not Allowed with an Allow header listing the methods the matching endpoints accept, and an empty body. MapGet registers GET only, so a HEAD or POST to that path gets 405, not 404.

open as a page

In ASP.NET Core 10, how does app.MapFallback decide which requests it handles, and why can it hide 404 and 405 responses from API clients?

level: middleimportance: should knowfreq 30%

basics

~20 s

MapFallback maps a catch-all {*path:nonfile} endpoint with Order int.MaxValue, so it runs only when nothing better matches. It accepts every method, so unknown /api URLs get its response instead of 404, and wrong methods reach it instead of a 405.

open as a page

In ASP.NET Core routing, how do the catch-all parameters {*path} and {**path} differ, and where in a template may one appear?

level: middleimportance: should knowfreq 38%

basics

~20 s

Both capture the rest of the path, slashes included, and match identically. They differ in URL generation: {*path} encodes a slash in the value as %2F, while {**path} keeps it, so the path round-trips. Either must be the template's last segment.

open as a page

Two ASP.NET Core 10 endpoints both handle GET /orders/{id} and requests fail with AmbiguousMatchException; how do precedence and Order decide, and how do you fix it?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Routing ranks candidates by Order, then template precedence; two valid candidates tied on both throw AmbiguousMatchException at request time, naming both endpoints. Remove the duplicate, make the templates differ, or give one a lower Order with WithOrder.

open as a page

In ASP.NET Core 10, what do WithMetadata, WithName and WithDisplayName attach to an endpoint, and how does custom middleware read that metadata?

level: seniorimportance: should knowfreq 35%

basics

~10 s

WithMetadata adds arbitrary objects to the endpoint's metadata; WithName adds an endpoint name used for link generation; WithDisplayName sets the label used in logs and errors. Middleware after routing calls GetEndpoint()?.Metadata.GetMetadata<T>() to read them.

open as a page

In ASP.NET Core 10, how do you build and register a custom IRouteConstraint that accepts only ISBN-13 book identifiers, and when is regex enough?

level: seniorimportance: should knowfreq 30%

basics

~10 s

Implement IRouteConstraint.Match to read values[routeKey] and run the ISBN-13 checksum, register it with RouteOptions.SetParameterPolicy under a name, then use {isbn:isbn13}. A regex constraint is enough when the shape matters but the checksum does not.

open as a page

In ASP.NET Core MVC, how are [controller] and [action] tokens in a [Route] template replaced, and how do you make them produce kebab-case URLs?

level: seniorimportance: should knowfreq 32%

basics

~20 s

When MVC builds attribute routes it replaces [controller], [action] and [area] with the controller name without its suffix, the action name and the area. An IOutboundParameterTransformer applied through RouteTokenTransformerConvention rewrites those values, for example BookSeries to book-series.

open as a page

In ASP.NET Core 10, how do RequireHost and the [Host] attribute restrict which requests an endpoint matches, and why are they not a security boundary?

level: seniorimportance: nice to knowfreq 18%

basics

~20 s

RequireHost and [Host] add host metadata that routing matches against the request's Host header and port; a non-matching host leaves the endpoint out, usually ending in 404. Clients control the Host header, so it routes traffic but does not authorize it.

open as a page