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?
answer
- one path segment per parameter
- ? = no value when absent
- = value always produces a value
- optional plus default is a parse error
- {controller=Home}/{action=Index}/{id?}
basics
~20 sA 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 sA 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 linesvar 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
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.
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.
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.
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.