8.4 — Route Templates, Parameters, Optionals and Defaults¶
← Roadmap · Section: 8. Routing Prev: 8.3 Conventional vs attribute routing · Next: 8.5 Route constraints
Markers: ⭐ 💻 · Confidence: 🔴 · Last reviewed: —
TL;DR¶
A route template is the pattern string describing which URLs an endpoint matches, with
{placeholders} for the parts you want to capture.
{id}is required,{id?}is optional,{id=5}has a default.{*rest}is a catch-all that swallows the remaining path, slashes included.- ⚠️ An optional parameter must be last. Anything after it can never be reached.
Definitions¶
| Term | What it is | What it means |
|---|---|---|
| Route template | a pattern string | "orders/{id}/lines/{lineNumber?}". Describes matching URLs. |
| Literal segment | fixed text | orders — must appear exactly. |
| Route parameter | a {placeholder} |
Captures a URL segment into a named value. |
| Optional parameter | {id?} |
May be omitted. Must be the last segment. |
| Default value | {id=5} |
Used when the segment is absent. Makes it effectively optional. |
| Catch-all | {*rest} or {**rest} |
Captures everything remaining, including slashes. |
| Round-trip catch-all | {**rest} |
Same, but does not re-encode slashes when generating links. |
| Route values | a dictionary | The captured values, on HttpContext.Request.RouteValues. |
| Complex segment | mixed literal and parameter | file-{name}.{ext}. Supported, with caveats. |
| Reserved names | action, controller, area, page, handler |
Have special meaning. Do not use them as your own parameters. |
The concept¶
Reading a template¶
Split it on slashes and each part is either literal text that must match exactly or a
{parameter} that captures whatever is there:
| Segment | Kind |
|---|---|
api |
Literal |
orders |
Literal |
{id} |
Required parameter |
lines |
Literal |
{lineNumber?} |
Optional parameter |
So it matches:
/api/orders/42/lines → id = "42", lineNumber absent
/api/orders/42/lines/3 → id = "42", lineNumber = "3"
/api/orders/lines/3 ✗ no match — {id} is required
A picture: a fill-in-the-blanks form. The printed words must be exactly right; the blanks accept whatever is written in them. A blank marked optional can be left empty — but only if it is at the end, because otherwise you cannot tell which blank was skipped.
⚠️ Why optionals must be last¶
That last point is the rule people get wrong:
Given /orders/lines/3, is lines the id, or was id omitted? The router cannot tell, so
everything after an optional parameter is unreachable.
Route parameters are matched positionally, segment by segment. Once one can be absent, the positions after it stop lining up.
How it works¶
The simple version — the four forms¶
// Required
app.MapGet("/orders/{id}", (string id) => $"Order {id}");
// /orders/42 ✓ /orders ✗
// Optional — must be last
app.MapGet("/orders/{id?}", (string? id) => id is null ? "All orders" : $"Order {id}");
// /orders/42 ✓ /orders ✓ (id is null)
// Default — behaves as optional, but supplies a value
app.MapGet("/orders/{page=1}", (int page) => $"Page {page}");
// /orders/3 ✓ (page=3) /orders ✓ (page=1)
// Catch-all — swallows the rest, INCLUDING slashes
app.MapGet("/files/{*path}", (string path) => $"File at {path}");
// /files/docs/2026/report.pdf → path = "docs/2026/report.pdf"
⚠️ {id?} and {id=default} differ in an important way. With ? the parameter is genuinely
absent, so a non-nullable target gets default(T) — zero for an int. With =1 the router
supplies the value, so it is always present:
app.MapGet("/orders/{page?}", (int page) => page); // /orders → page = 0
app.MapGet("/orders/{page=1}", (int page) => page); // /orders → page = 1
Prefer a default over an optional for numbers, because a silent zero is rarely what you want (7.5 has the same trap in configuration).
Catch-all parameters¶
Two forms, and the difference only shows up when generating links:
app.MapGet("/files/{*path}", (string path) => path); // single star
app.MapGet("/docs/{**path}", (string path) => path); // double star
Both capture the remaining path with slashes intact. The double star is "round-trippable" — it
does not re-encode the slashes when the URL is generated back
(8.6). Since generating a link to a catch-all is common for file paths
and slugs, {**path} is usually the better choice.
⚠️ A catch-all must be the last segment, and it matches an empty string too — so
/files/ matches with path as "".
Complex segments¶
A segment can mix literal text and parameters:
app.MapGet("/reports/{year}-{month}.pdf", (int year, int month) => $"{year}/{month}");
// /reports/2026-08.pdf → year = 2026, month = 8
⚠️ These work, and they are fragile. The router splits on the literal parts, so ambiguity
causes surprising results — and two adjacent parameters with no literal between them
({a}{b}) are rejected outright, because there is no way to know where one ends.
Prefer separate segments unless the format genuinely requires it:
How it actually works — reserved parameter names¶
Some names have special meaning and must not be used for your own parameters:
| Name | Used by |
|---|---|
controller |
Conventional routing, to pick the controller |
action |
Conventional routing, to pick the action |
area |
Areas (8.8) |
page |
Razor Pages |
handler |
Razor Pages handler methods |
⚠️ page is the one that bites, because it is such a natural name for pagination:
In an MVC or minimal API application this usually works, but in an app that also uses Razor
Pages it can produce very confusing behaviour. Use pageNumber, or pass it as a query string
parameter, which is more RESTful for pagination anyway
(10.7).
Matching is case-insensitive¶
⚠️ But the captured value keeps its original casing. So {slug} from /Products/Blue-Widget
is "Blue-Widget", not lowercased. If you compare it against a database value, use an explicit
StringComparison (1.3).
The deeper detail — what a template does not do¶
⚠️ Route templates only match the path. They do not see:
- The query string —
?page=2is not part of routing. It is bound separately (11.1). - The HTTP method — that comes from
[HttpGet]orMapGet, which is metadata, not the template. - Headers or the body.
So this does not work:
The correct form binds it from the query:
That distinction — path is routed, query is bound — comes up regularly and is worth being clear about.
Code¶
A realistic controller showing the template forms:
[ApiController]
[Route("api/[controller]")]
public class OrdersController(IOrderService orders) : ControllerBase
{
// GET /api/orders — no parameters, query string for paging
[HttpGet]
public async Task<IActionResult> List(
[FromQuery] int pageNumber = 1, // query, NOT a route parameter
[FromQuery] int pageSize = 20,
CancellationToken ct = default)
=> Ok(await orders.ListAsync(pageNumber, pageSize, ct));
// GET /api/orders/{id} — required, constrained
[HttpGet("{id:guid}")]
public async Task<IActionResult> Get(Guid id, CancellationToken ct)
=> await orders.GetAsync(id, ct) is { } o ? Ok(o) : NotFound();
// GET /api/orders/{id}/lines/{lineNumber}
[HttpGet("{id:guid}/lines/{lineNumber:int}")]
public async Task<IActionResult> GetLine(Guid id, int lineNumber, CancellationToken ct)
=> await orders.GetLineAsync(id, lineNumber, ct) is { } l ? Ok(l) : NotFound();
// GET /api/orders/history/2026/08 — defaults, so /history works too
[HttpGet("history/{year:int=2026}/{month:int=1}")]
public async Task<IActionResult> History(int year, int month, CancellationToken ct)
=> Ok(await orders.HistoryAsync(year, month, ct));
}
Two deliberate choices:
Paging is query string, not route. /api/orders?pageNumber=2 is the conventional REST shape,
and it avoids the reserved page name entirely.
Defaults rather than optionals for the date parts, so year and month are always real
values rather than silently zero.
A catch-all for file paths¶
// GET /files/documents/2026/august/report.pdf
[HttpGet("/files/{**path}")]
public async Task<IActionResult> Download(string path, CancellationToken ct)
{
// ⚠️ NEVER build a file path directly from user input — path traversal.
// The catch-all happily captures "../../appsettings.json".
var file = await _files.FindByLogicalPathAsync(path, ct);
if (file is null) return NotFound();
return PhysicalFile(file.PhysicalPath, file.ContentType, file.OriginalName);
}
⚠️ That warning is the important part of this example. A catch-all captures slashes, so it
will happily capture ../../secrets. Look the path up in a database or validate it against an
allow-list — never pass it to Path.Combine against a root directory. See
17.11.
Interview questions¶
Q: What is the difference between {id?} and {id=5}?
Both make the segment omittable, but they behave differently when it is absent. With {id?} the
parameter genuinely is not supplied, so a non-nullable target receives default(T) — zero for an
int, which is rarely what you want. With {id=5} the router supplies the default value, so the
parameter is always present with a real value. For numeric parameters I would use a default
rather than an optional, because a silent zero is easy to miss.
Q: Why must an optional route parameter be last?
Because segments are matched positionally. Once a parameter can be absent, the positions after it
no longer line up — given /orders/lines/3 against orders/{id?}/lines/{lineNumber}, the router
cannot tell whether lines is the id or whether the id was omitted. So anything after an
optional parameter is unreachable.
Q: What is a catch-all parameter?
A parameter written {*path} or {**path} that captures the entire remaining path including
slashes, rather than a single segment. It suits file paths and hierarchical slugs. The double-star
form is round-trippable, meaning it does not re-encode the slashes when a link is generated back
from it, so it is usually the better choice. Two cautions: it must be the last segment, and
because it captures slashes it will happily capture path traversal sequences — so never build a
file system path from it directly.
Q: Can a route template match on the query string?
No. Templates match the path only. The query string is not part of routing at all — it is handled
by model binding, so you take it as a parameter with [FromQuery]. The HTTP method is also not
part of the template; that comes from the [HttpGet]-style attribute, which is endpoint metadata.
Writing something like [HttpGet("orders?status={status}")] does not work, and that path-versus-query
distinction is worth being clear on.
Traps ⚠️¶
- An optional parameter must be last. Anything after it is unreachable.
{id?}givesdefault(T)when absent — zero for an int.{id=1}gives a real value.- A catch-all captures slashes, including
../. Never build a file path from it. pageis reserved by Razor Pages. UsepageNumber, or a query string parameter.controller,action,areaandhandlerare also reserved.- Query strings are not route segments. Use
[FromQuery]. - Matching is case-insensitive but captured values keep their casing.
- Two adjacent parameters with no literal between them are rejected —
{a}{b}will not compile as a template. - A catch-all matches an empty string, so
/files/matches with an empty path.
Related¶
- 8.3 Conventional vs attribute routing — where templates are declared
- 8.5 Route constraints — restricting what a parameter accepts
- 8.6 Link generation — why
{**path}round-trips - 8.10 Catch-all routes and slugs — the SEO use case
- 11.1 Binding sources — route versus query
- 10.7 Pagination — why paging belongs in the query
- 17.11 Path traversal — the catch-all risk