📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do routing and navigation work in Blazor? Explain @page route templates and constraints, the Router component, NavigationManager and query-string parameters, how to stop users losing unsaved changes, and what enhanced navigation does in a Blazor Web App compared with interactive client-side routing.

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.

Mid-Level Theory Intermediate aspnet-core blazor enhanced-navigation frontend navigation routing

🎯 Key points

  • @page "/orders/{Id:int}" creates a route; constraints only match, they do not validate business rules
  • Router in Routes.razor scans AppAssembly and AdditionalAssemblies; .NET 10 uses NotFoundPage and NavigationManager.NotFound() for a real 404
  • NavigationManager.NavigateTo(uri, forceLoad, replace), LocationChanged; [SupplyParameterFromQuery] + GetUriWithQueryParameters keep filters and paging in the URL so refresh, back and shared links keep state
  • Same component instance is reused across route changes: load data in OnParametersSetAsync
  • <NavigationLock> with OnBeforeInternalNavigation (ctx.PreventNavigation()) and ConfirmExternalNavigation (beforeunload) protects unsaved changes
  • Enhanced navigation: blazor.web.js fetches the next page and patches the DOM instead of a full reload; opt out with data-enhance-nav="false"
  • Global interactivity on Routes = client-side routing inside the circuit/WASM; otherwise each navigation is a server request

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"In Blazor, routing is attribute-based. @page "/orders/{Id:int}" compiles to a [Route] attribute on the component, and the Router component in Routes.razor scans the app assembly, plus any AdditionalAssemblies such as the .Client project, to build the route table. Constraints like :int or :guid only decide whether the route matches; they are not validation. For a missing record I call NavigationManager.NotFound(), which is new in .NET 10: it renders the NotFoundPage and, 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"), with replace: true to avoid filling the history, or forceLoad: true to bypass Blazor and do a full browser load. Query strings bind with [SupplyParameterFromQuery], and GetUriWithQueryParameter builds a new URL for filters, which keeps state shareable. One thing people miss: moving from /orders/1 to /orders/2 reuses the same component instance, so data loading belongs in OnParametersSetAsync, not OnInitializedAsync. For unsaved changes I put a NavigationLock on the form with ConfirmExternalNavigation for tab closes and an OnBeforeInternalNavigation callback 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.js intercepts link clicks, fetches the new page with fetch, and patches the DOM: that is enhanced navigation. It keeps scroll position and avoids a full reload, but it is still server rendering. If Routes has 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 on DOMContentLoaded and breaks after the first enhanced navigation, because no full page load happens."


Route templates

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

Navigation tools

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

Enhanced navigation vs interactive routing

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

Production example

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.

🔍 What the interviewer is checking

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

  • Loads data in OnParametersSetAsync because the instance is reused
  • Knows enhanced navigation is server rendering patched into the DOM
  • Mentions NavigationManager.NotFound() and correct status codes
  • Puts shareable state in the URL and protects pages with [Authorize]

Red flags

  • Thinks every Blazor app does client-side routing
  • Uses forceLoad to "fix" stale data
  • Treats hidden links as security

📚 Learn in depth

1. How the route table is built

The 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 -&gt;

💻 Code

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

⚠ Common mistakes

  • Mistake: Loading data only in 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.
  • Mistake: Treating route constraints as validation. Why it is wrong: {Id:int} only affects matching; a negative or unknown id still reaches the page. Instead: validate and call NotFound() or show an error.
  • Mistake: Returning a friendly "not found" message with status 200. Why it is wrong: search engines index it and monitoring misses broken links. Instead: use NavigationManager.NotFound() in .NET 10.
  • Mistake: Using 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.
  • Mistake: Relying on 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.
  • Mistake: Hiding links instead of protecting routes. Why it is wrong: users can type the URL. Instead: [Authorize] on the page and authorisation on the API.
  • Mistake: Keeping filter and paging state in a scoped service or component fields. Why it is wrong: a refresh, the Back button or a shared link resets the list to page 1 with no filters. Instead: bind ?status=open&page=3 with [SupplyParameterFromQuery] and navigate with GetUriWithQueryParameters (use replace: true for keystroke-level changes so history does not fill up).
  • Mistake: Only handling internal navigation with NavigationLock. Why it is wrong: closing the tab or typing a new URL bypasses OnBeforeInternalNavigation. Instead: also set ConfirmExternalNavigation while the form is dirty.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says Blazor pages are mapped as ASP.NET Core endpoints Why: Checks understanding of endpoint routing, precedence and metadata underneath Blazor's routes
    How to answer

    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.

  2. When: Candidate contrasts enhanced navigation with global interactivity Why: Checks whether they can link navigation behaviour back to the render mode choice
    How to answer

    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.

  3. When: Candidate compares Blazor routing with SPA client-side routing Why: Checks whether they know the server fallback and deep-link issues of hosting a JavaScript SPA
    How to answer

    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).

🛠 Real-world problems: how you handle them

Users see the previous order after clicking 'Next order'
Situation
An internal Blazor Server app for [the warehouse team, ~150 users] showed order details at /orders/{id} with Next/Previous links. After a redesign, staff reported picking the wrong order because the screen showed stale data.
Signals
Support tickets saying the URL changed but the page did not; Application Insights showed the order API called only once per session for that page; no exceptions logged.
Investigation
Reproduced locally with browser dev tools: the URL changed via pushState but no WebSocket message triggered a data load. Added logging to lifecycle methods and saw `OnInitializedAsync` ran once while `OnParametersSetAsync` ran on every click. The load code lived in `OnInitializedAsync`.
Resolution
Immediate: moved loading into `OnParametersSetAsync` guarded by a loadedId check and cleared the old order while loading so stale data could not show. Long term: added `NavigationManager.NotFound()` for unknown ids and a 'Loading order N' heading so the screen always states which order it shows.
Prevention
A bUnit test that sets Id=1 then Id=2 and asserts the second order renders; a code review checklist item for route-parameter pages; a Playwright test that clicks Next and checks the order number.

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.

More in Blazor

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me