skip to content

Page Routes & Navigation

Routable components declare @page templates the Router matches; NavigationManager navigates, and enhanced navigation patches the DOM. Interviewers probe not-found handling and forced reloads.

on this pageshow

explore

questions

6

In a Blazor Web App, how does an @page directive make a component routable, and how do route parameters and constraints reach it?

level: juniorimportance: must knowfreq 62%

answer

  1. compiled into an attribute
  2. RouteAttribute, AllowMultiple = true
  3. AppAssembly plus AdditionalAssemblies
  4. [Parameter] property, name case-insensitive
  5. constraint miss means no match

basics

~20 s

The Razor compiler turns @page into a [Route] attribute that Blazor's routing reads. A {Name} segment fills the [Parameter] property of that name, and a typed constraint such as {Id:int} filters the match and converts the value.

solid answer

~40 s

`@page "/plants/{Id:int}"` compiles to `[Route("/plants/{Id:int}")]` on the generated class. In a Blazor Web App, `MapRazorComponents<App>()` turns every routable component into an endpoint for static rendering, and the `Router` in `Routes.razor` scans `AppAssembly` (plus `AdditionalAssemblies`) for interactive routing. A route value is passed as a component parameter, so the page needs a `[Parameter]` property whose name matches case-insensitively. A constraint that fails means the template does not match at all, so `/plants/monstera` ends in not-found handling instead of a binding error. Only the typed constraints `bool`, `datetime`, `decimal`, `double`, `float`, `guid`, `int` and `long` convert the text; an unconstrained segment arrives as a `string`. A page may carry several `@page` lines, an optional `{Section?}` segment, or a catch-all `{*Path}`.

code

razor · 9 lines
razor
@* Routes.razor *@
<Router AppAssembly="typeof(Program).Assembly"
        AdditionalAssemblies="new[] { typeof(Nursery.Catalog.CatalogMarker).Assembly }"
        NotFoundPage="typeof(Pages.NotFound)">
    <Found Context="routeData">
        <RouteView RouteData="routeData" DefaultLayout="typeof(Layout.MainLayout)" />
        <FocusOnNavigate RouteData="routeData" Selector="h1" />
    </Found>
</Router>

go deeper

for a junior

Recall that @page becomes a [Route] attribute, that a {Name} segment fills a [Parameter] property of that name, and that {Id:int} both filters and converts.

for a middle

Explain the two route consumers in a Blazor Web App, MapRazorComponents and the Router, which constraints convert values, and why a missing template parameter arrives as null.

for a senior

Show you can diagnose pages that render only after a reload, constraint misses that look like broken links, and root templates that capture static files.

for a principal

Discuss keeping route templates in shared constants for large teams, and when to split pages across class libraries given the two assembly lists that must stay in sync.

## What `@page` compiles to A **routable component** is a `.razor` component that can be reached by a URL. The `@page` directive is what makes it routable. When the project builds, the Razor compiler turns the directive into a **`RouteAttribute`** (`[Route(...)]`) on the generated C# class. Nothing is registered at run time by the component itself: routing reads attributes that already exist in the compiled assembly. For an online nursery, a plant page looks like this: ```razor @page "/plants/{Id:int}" @page "/plants/{Id:int}/care/{Section?}" <h1>Plant @Id</h1> @code { [Parameter] public int Id { get; set; } [Parameter] public string? Section { get; set; } } ``` `RouteAttribute` is declared with `AllowMultiple = true`, so one component can answer several templates, and with `Inherited = false`, so a component that derives from a routable base class does not silently take over the base's URL. The template can also come from a constant through `@attribute [Route(PlantRoutes.Details)]` when several files must agree on one path. ## Who reads the route table A Blazor Web App has two consumers of those attributes: | Consumer | Where it is set up | When it routes | |---|---|---| | Endpoint routing | `app.MapRazorComponents<App>()` in `Program.cs` | every request rendered on the server (static SSR and prerendering) | | The `Router` component | `<Router AppAssembly="typeof(Program).Assembly">` in `Routes.razor` | navigations handled in the browser once the router is interactive | Both only see the assemblies they are told about. Pages that live in a Razor class library or in the `.Client` project need `AdditionalAssemblies` on the `Router` and `.AddAdditionalAssemblies(...)` on `MapRazorComponents`; forget one and the page works in one mode and is missing in the other. ## How route values become parameters When a template matches, the router creates a `RouteData` with the page type and the route values, and `RouteView` renders the page, passing each value as a **component parameter**. That has three consequences: - The receiving property needs `[Parameter]`. A plain public property with the right name is rejected with an `InvalidOperationException` saying it lacks a parameter-supplying attribute. - Names match case-insensitively: `{id}` fills `Id`. - When a page declares several templates, a parameter missing from the matched one is supplied as `null`. A value-type property then receives its default (`0` for `int`), so declare it nullable (`int?`) when "absent" must differ from zero; `string? Section` above already can be `null`. ## Constraints filter, and a few convert A **route constraint** follows a colon inside the braces. It decides whether the template matches the URL at all. If `/plants/monstera` is requested, `{Id:int}` rejects the segment and the router keeps looking; when nothing else matches, the request goes to not-found handling. It is never a 400 response and never a page rendered with `Id = 0`. The router also converts the text for the typed constraints, using the invariant culture: | Constraint | CLR type the parameter receives | |---|---| | `bool` | `bool` | | `datetime` | `DateTime` | | `decimal`, `double`, `float` | the matching numeric type | | `guid` | `Guid` | | `int`, `long` | `int`, `long` | Any other segment arrives as a `string`. So `@page "/plants/{Id}"` with `[Parameter] public int Id` compiles, matches, and then fails when the framework tries to assign the string to the `int` property. Blazor resolves constraints with ASP.NET Core's own inline constraint resolver, so the wider constraint syntax shared with server routes is accepted too, but only the types above change the value's type. A `regex` constraint does not work in the WebAssembly runtime unless the app turns on an `AppContext` switch for it. ## Optional and catch-all segments 1. `{Section?}` makes the last segment optional; the property receives `null` when it is absent. 2. `{*Path}` is a **catch-all** that captures the rest of the path, slashes included, as one `string`, which suits a nursery's `/guides/{*Path}` knowledge base. 3. A template like `/{slug?}` at the root also captures file requests such as the app's stylesheet; the `nonfile` constraint (`/{slug:nonfile?}`) stops that. ## Mistakes that come up - Expecting `[Parameter]` to be optional for route values, as it is for query-string values since .NET 8. - Declaring `int Id` without a constraint and blaming the router for the failure. - Adding a page to a class library and seeing it only after a full page reload, because only one of the two assembly lists was updated. - Reading a constraint as validation: it shapes matching, and the page still has to handle a well-formed id that names no plant.

  • A plant page lives in a Razor class library. It renders after a full reload but not after an in-app link click. What is missing?
    Interactive routing only knows the assemblies given to the `Router`. The server endpoint was registered with `MapRazorComponents<App>().AddAdditionalAssemblies(...)`, so a fresh request renders, but `Routes.razor` still lacks `AdditionalAssemblies="new[] { typeof(SomeType).Assembly }"`. Both lists must name the library.
  • Why does a page with @page "/plants" and @page "/plants/{Id:int}" usually declare Id as int?
    When `/plants` matches, the router still supplies every parameter name used by the component's templates and passes `null` for the ones the matched template lacks. An `int` property silently turns that `null` into `0`, so the page cannot tell "no id" from id 0; `int?` keeps the difference and lets the page branch on `Id is null`.
  • How do you stop @page "/{Slug?}" at the site root from swallowing requests for static files?
    Use the `nonfile` constraint: `@page "/{Slug:nonfile?}"`. Without it the optional segment also matches paths such as `Nursery.styles.css` or `favicon.ico`, so the page renders where the file should have been served.

  • A value that fails {Id:int} reaches the page and produces a 400 Bad Request
  • Every route segment is converted to the property type, so {Id} fills an int property
  • A plain public property without [Parameter] receives the route value
  • A component can declare only one @page directive
  • The Router finds pages in referenced class libraries without AdditionalAssemblies
open as a page

In Blazor, what does NavigationManager.NavigateTo do with forceLoad false versus true, and when must you force a full page load?

level: middleimportance: must knowfreq 55%

basics

~20 s

With forceLoad false, the default, NavigateTo stays inside Blazor: the interactive router swaps components or enhanced navigation patches the page. forceLoad true loads a new document, which non-Blazor endpoints and a fresh app state need.

open as a page

In a Blazor Web App, how does [SupplyParameterFromQuery] bind catalog filters from the query string, and how should a page update those filters?

level: middleimportance: should knowfreq 44%

basics

~20 s

[SupplyParameterFromQuery] fills a property from the query string key of the same name, or from Name. To change a filter, build the URL with NavigationManager.GetUriWithQueryParameter(s) and call NavigateTo; the same page instance receives new values and OnParametersSet runs.

open as a page

In a Blazor Web App, how does enhanced navigation work, what can it break, and how do you opt a link or page out of it?

level: seniorimportance: should knowfreq 36%

basics

~20 s

Enhanced navigation lets blazor.web.js intercept an internal link, fetch the page and patch the returned HTML into the current DOM instead of loading a new document. Turn it off per link or subtree with data-enhance-nav="false", or with forceLoad in code.

open as a page

In ASP.NET Core 10 Blazor, how do Router's NotFoundPage and NavigationManager.NotFound() handle a plant id that does not exist, across render modes?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Router.NotFoundPage names a routable component shown when nothing matches; a page calls NavigationManager.NotFound() when its data is missing. Under static SSR and prerendering that sets a 404 and renders the page; interactively only global routers show it.

open as a page