Covers Blazor routing (@page templates, constraints, catch-all, Router and NotFoundPage), NavigationManager (NavigateTo, NotFound, LocationChanged), SupplyParameterFromQuery, NavigationLock, and enhanced navigation versus interactive routing in .NET 10 Blazor Web Apps.
A component becomes a page with @page "/orders/{Id:int}". The Router in Routes.razor finds routable components in the app assembly (and AdditionalAssemblies) and renders the match inside a layout. NavigationManager navigates in code (NavigateTo, with forceLoad and replace), exposes LocationChanged, and in .NET 10 has NotFound() for a real 404. [SupplyParameterFromQuery] binds query strings, and NavigationLock stops users leaving with unsaved changes.
In a Blazor Web App without global interactivity, each navigation is a server request, but enhanced navigation in blazor.web.js fetches the page and patches the DOM so it feels like an SPA. With an interactive mode on Routes, routing happens client-side in the circuit or WebAssembly. The trade-off is server rendering per page versus a long-lived interactive session.
"In Blazor, routing is attribute-based.
@page "/orders/{Id:int}"compiles to a[Route]attribute on the component, and theRoutercomponent inRoutes.razorscans the app assembly, plus anyAdditionalAssembliessuch as the.Clientproject, to build the route table. Constraints like:intor:guidonly decide whether the route matches; they are not validation. For a missing record I callNavigationManager.NotFound(), which is new in .NET 10: it renders theNotFoundPageand, under static SSR, returns a real 404 status instead of a 200 with an apology.For navigation in code I inject
NavigationManager:NavigateTo("/orders/42"), withreplace: trueto avoid filling the history, orforceLoad: trueto bypass Blazor and do a full browser load. Query strings bind with[SupplyParameterFromQuery], andGetUriWithQueryParameterbuilds a new URL for filters, which keeps state shareable. One thing people miss: moving from/orders/1to/orders/2reuses the same component instance, so data loading belongs inOnParametersSetAsync, notOnInitializedAsync. For unsaved changes I put aNavigationLockon the form withConfirmExternalNavigationfor tab closes and anOnBeforeInternalNavigationcallback that can cancel.The interesting part in a Blazor Web App is how navigation happens. If the app is not globally interactive, each page is a server request, but
blazor.web.jsintercepts link clicks, fetches the new page withfetch, and patches the DOM: that is enhanced navigation. It keeps scroll position and avoids a full reload, but it is still server rendering. IfRouteshas an interactive render mode, routing is client-side inside the circuit or the WebAssembly runtime. The mistake I see is third-party JavaScript that runs onDOMContentLoadedand breaks after the first enhanced navigation, because no full page load happens."
| Template | Matches |
|---|---|
@page "/orders" |
Exact path |
@page "/orders/{Id:int}" |
/orders/42; Id bound to [Parameter] int Id |
@page "/orders/{Id:int?}" |
Optional segment |
@page "/files/{*Path}" |
Catch-all |
Multiple @page lines |
Several URLs for one component |
| API | Use |
|---|---|
NavigateTo(uri, forceLoad, replace) |
Navigate in code |
NavigationManager.NotFound() (.NET 10) |
Render the not-found page; 404 under SSR |
LocationChanged event |
React to URL changes (unsubscribe on dispose) |
[SupplyParameterFromQuery] |
Bind ?status=open&page=2 |
GetUriWithQueryParameter(s) |
Build filter URLs |
<NavLink Match="..."> |
Links with an active class |
<NavigationLock> |
Block or confirm navigation away |
| Static SSR + enhanced navigation | Global interactive (Server/WASM) | |
|---|---|---|
| Who renders the next page | Server, full request | Circuit or browser |
| DOM update | Fetched HTML diffed into the page | Render batch |
| State between pages | Lost unless persisted | Scoped services keep it |
| Server memory | None between requests | Circuit per tab (Server) |
| Opt out | data-enhance-nav="false" or forceLoad |
forceLoad: true |
A catalogue site served [~40,000] daily visitors with static SSR. Turning on enhanced navigation (the default) and moving filters into the query string made page changes feel instant, kept filters bookmarkable, and avoided any circuits. The only breakage was an analytics script that only fired on full loads, which we fixed by listening to Blazor's enhancedload event.
Checks that the candidate understands Blazor routing beyond @page, including instance reuse, real 404s, unsaved-change protection and how Blazor Web Apps navigate.
Green flags
OnParametersSetAsync because the instance is reusedNavigationManager.NotFound() and correct status codes[Authorize]Red flags
forceLoad to "fix" stale dataThe Razor compiler turns each @page "/orders/{Id:int}" into [Route("/orders/{Id:int}")] on the generated component class. At start-up the Router reflects once over AppAssembly and AdditionalAssemblies, collects every type with a RouteAttribute, parses the templates and builds a route table ordered by precedence: literal segments beat parameters, constrained parameters beat unconstrained ones, and catch-alls come last. The table is cached, so matching on each location change is a cheap in-memory lookup, not reflection.
App.razor ->
An order details page that loads on parameter change, returns a real 404, binds a query string and blocks leaving with unsaved edits.
@* OrderDetails.razor *@
@page "/orders/{Id:int}"
@rendermode InteractiveServer
@attribute [Authorize]
@inject IOrderService Orders
@inject NavigationManager Nav
OnInitializedAsync on a page with a route parameter. Why it is wrong: navigating between ids reuses the instance, so the old record stays on screen. Instead: load in OnParametersSetAsync when the id changes.{Id:int} only affects matching; a negative or unknown id still reaches the page. Instead: validate and call NotFound() or show an error.NavigationManager.NotFound() in .NET 10.forceLoad: true everywhere. Why it is wrong: it throws away the circuit or WASM state and reloads everything. Instead: use it only to leave the Blazor app or reset state on purpose.DOMContentLoaded for page scripts in a Blazor Web App. Why it is wrong: enhanced navigation does not reload the document, so the script runs once. Instead: listen to enhancedload, use a JS module per component, or mark the element data-permanent.[Authorize] on the page and authorisation on the API.?status=open&page=3 with [SupplyParameterFromQuery] and navigate with GetUriWithQueryParameters (use replace: true for keystroke-level changes so history does not fill up).NavigationLock. Why it is wrong: closing the tab or typing a new URL bypasses OnBeforeInternalNavigation. Instead: also set ConfirmExternalNavigation while the form is dirty.Navigation is where the Blazor Web App model shows its two halves. With static SSR and enhanced navigation every page is a stateless request: easy to scale, cache and monitor, but any in-memory state is gone between pages. With global interactivity the app behaves like an SPA, but in Server mode each tab costs a circuit. I choose per app, and I keep URLs meaningful either way: ids in the path, filters in the query, so pages are bookmarkable and supportable.
| Approach | When it fits | Cost | When not to |
|---|---|---|---|
| Static SSR + enhanced navigation | Public, read-heavy sites | Page state lost between requests | Complex multi-step editors |
| Global Interactive Server routing | Internal LOB apps | Circuit per tab, sticky sessions | Large public audiences |
| Global WebAssembly routing | Rich client apps at scale | First download, API for everything | Low-end devices |
| Query-string state | Filters, paging, tabs | URL length, must validate input | Sensitive data (logged in proxies) |
I measure navigation with Application Insights page views and browser timing, and check 404 rates after releases to catch broken links.
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.
A Blazor Web App decides per component where rendering happens. Static SSR (the default) renders HTML on the server for each request with no live interactivity, like Razor Pages. Interactive Server keeps component state on the server in a circuit and sends UI diffs over a SignalR WebSocket. Interactive WebAssembly downloads the .NET runtime and your assemblies and runs components in the browser, calling your API over HTTP. Interactive Auto starts on Server for a fast first load, then uses WebAssembly on later visits once the bundle is cached.
Interactive modes prerender on the server by default. The trade-off: Server is quick to start and keeps code private, but costs latency on every click and memory per connected user; WebAssembly scales cheaply but has a multi-megabyte first download.
There are two shapes. Same origin: build the SPA into the API's wwwroot, serve it with static files and MapFallbackToFile("index.html") so deep links work, or put both behind one reverse proxy (YARP, Front Door). You get no CORS, first-party cookies and easy BFF security. Separate origins: host the SPA on Azure Static Web Apps or a CDN and call the API on another host. You get independent deploys and edge caching, but you must configure CORS and your cookies become cross-site, pushing you towards tokens in the browser.
Locally, the Vite dev server serves the SPA with hot reload and proxies /api to Kestrel, so the browser sees one origin, just like production same-origin hosting.
The trade-off is security and simplicity (same origin) against independent scaling and release cadence (separate origins).
How to tell it (STAR)
**S:** Our warehouse Blazor Server app at [company] had Next/Previous links on order details, and after a redesign pickers reported seeing the previous order. **T:** As [my role] I had to find the cause fast because wrong picks cost money. **A:** I reproduced it with dev tools, saw the URL change with no data load, logged the lifecycle and found the load in `OnInitializedAsync`, which does not run again because Blazor reuses the component instance. I moved it to `OnParametersSetAsync`, cleared the screen while loading, and added a bUnit test and a Playwright check. **R:** Wrong-order picks reported dropped from [about 12 a week] to zero, and the test has caught the same pattern in [two] other pages since.
Last updated 23 Nov 2026.