SharpRuneOpen playground

Routing and route parameters

Give pages addresses with @page templates, read route and query values, and move between pages with NavLink and NavigationManager.

  • 25 min
  • Read, predict, then run
Blazor WebAssembly project

In the SharpRune app for iPhone and iPad, tap Run in Preview: the app compiles the Razor components on the device and runs the project on .NET 9. On a computer, download the project and run it with the .NET 9 SDK. The separate C# companion practice below runs in this browser.

At a glance

Which @page template wins

AddressWhat the Router does
hello/Ada/hello/{Name?} sets Name = "Ada"
hello/hello/{Name?} sets Name = null
products with ?sort=price/products; sort gets "price"
products/2/products/{Id:int} sets Id = 2
products/abc{Id:int} fails, so NotFound
products/2/extrano template fits, so NotFound

The Router matches the address in the browser, with no server request. A failed constraint means no match, not a bad value; query values need [SupplyParameterFromQuery].

How the Router finds a page

When you write @page "/products" at the top of a .razor file, the Razor compiler turns it into a [Route("/products")] attribute on the generated component class. A component can carry several of these attributes, which is how Home in RoutingLab answers both / and /hello/{Name?}. Nothing else registers a page. The Router component in App.razor receives AppAssembly, looks for classes with route attributes in that assembly and builds a route table from their templates.

The Router listens to NavigationManager. Each time the address changes, through a link, a NavigateTo call or the browser's back button, it takes the part of the address after the base href, leaves the query string aside and tries the templates. More specific templates are tried first, so a literal segment wins over a parameter in the same position. If a template matches, the Router passes a RouteData object to its Found fragment, and RouteView creates the page component, wraps it in a layout if one is set and passes the route values as parameters. If nothing matches, the Router renders the NotFound fragment. All of this happens in the browser. No request goes to a server for the new page, so switching pages costs no network round trip.

Route parameters, constraints and optional segments

A segment in braces is a route parameter. The Router assigns its value to the component property with the same name, ignoring case, and that property needs the [Parameter] attribute. Without a constraint the value arrives as a string, so the property should be a string. A constraint after a colon restricts the match and sets the type at the same time: {Id:int} only matches a segment that parses as an int with the invariant culture, and the property receives an int. Blazor also has constraints such as bool, datetime, decimal, double, float, guid and long, and a catch-all parameter such as {*path} that takes the rest of the address.

A constraint is part of matching. products/abc does not reach ProductDetails with a bad value. The template fails, no other template fits, and the Router shows NotFound. On the other hand, products/99 matches, because 99 is a valid int, even though no product has that id. Treat constraints as a description of the address format, not as validation of your data.

A question mark makes a parameter optional. With /hello/{Name?}, both hello and hello/Ada match. When the segment is missing, the Router sets the property to null, so its type must allow null. RoutingLab shows this on a component with two templates: going from hello/Ada back to / sets Name to null again instead of keeping Ada.

Trace RoutingLab

Start at App.razor. It holds a header with two NavLink components and, below it, the Router. Because the header is outside the Router, it stays on screen while pages change; the next lesson moves it into a layout. The Router gets typeof(App).Assembly, so it finds the four route attributes of Home, Products and ProductDetails. The NotFound fragment prints the address that failed, which App.razor reads from the injected NavigationManager.

Tap products/2 on Home. The Router matches /products/{Id:int}, converts the text 2 to the int 2 and creates ProductDetails with Id set to 2. OnParametersSet looks the id up in Products.Catalog and finds the notebook. Tap Next. The address becomes products/3, the same template matches, and the Router reuses the ProductDetails instance: Id changes to 3, OnParametersSet runs again and the backpack appears. Tap Back to the list, by price. The button calls NavigateTo("products?sort=price"), the Router switches to Products, and its [SupplyParameterFromQuery] property receives price. The Products link in the header stays active through all of these steps, because each address starts with products followed by a slash or a question mark.

Common mistakes

A leading slash in a link, such as href="/products", ignores the base href. It works while the app is hosted at the root of a site and breaks when the app moves to a sub-path. Write relative links such as products and let the base element resolve them.

Two pages with the same template make the route ambiguous, and the Router throws an exception when it builds its route table. A parameter in a template without a matching [Parameter] property also fails, at the moment the Router tries to pass the value. Read error messages from the Router literally: they name the template and the component.

The most frequent routing bug is reading a route parameter only in OnInitialized. It works for the first address, then the page stops updating when only the parameter changes, because the component is reused. Compute from parameters in OnParametersSet, as ProductDetails does. Finally, remember that NavLinkMatch.All compares the query string in .NET 9, so a Match All link to products is not active on products?sort=price.

Practice

Add a page at /products/{Id:int}/reviews that shows the product name and a short fixed list of reviews, and link to it from ProductDetails. Then add a page at /orders/{OrderId:guid}. Before you test it, write down what you expect for a valid guid and for the word test.

In Products, add [SupplyParameterFromQuery] private int? Max { get; set; } and show only products whose price is at most Max. Build the filter links with Navigation.GetUriWithQueryParameter("max", 20) so that the current sort value stays in the address. Then extend the console companion with a /files/{*path} template and check which addresses it captures.

Review

Routing in Blazor WebAssembly is a lookup in the browser: from the address to a component type, and from address segments to parameter values.

Key points
  • @page compiles to a route attribute. The Router collects them from AppAssembly and picks the most specific template that matches.
  • {Id:int} restricts the match and sets the type. A failed constraint leads to NotFound, not to a bad value.
  • {Name?} is optional and becomes null when the segment is missing. The Router reuses a page component when only its parameters change.
  • [SupplyParameterFromQuery] reads query values. Since .NET 8 it needs no [Parameter] and can be private.
  • NavLink adds the active class; use NavLinkMatch.All for the home link. NavigationManager.NavigateTo moves in code without reloading the app.
Runs on this device: SharpRune compiles the Razor components and C# here and runs the app in Preview on .NET 9 WebAssembly. The same files run on a computer with the .NET 9 SDK and dotnet run.

Routing and route parameters — Blazor WebAssembly project

Run the project

  1. Tap Run in Preview. SharpRune copies these files into a new project, compiles the Razor components on this device and opens the app in Preview.
  2. On Home, tap each address in the list: hello/Ada, hello, products?sort=price, products/2, products/abc and nowhere. Watch the heading, the Name value and which header link is highlighted.
  3. On Products, switch between By name and By price, then type 9 in the number box and tap Open.
  4. Change a .razor file and tap Run again to rebuild.
  5. On a computer: install the .NET 9 SDK, save the files with their folders, and run dotnet run in that folder.

Download the project ↗

Project files

RoutingLab.csprojDownload file ↗
RoutingLab.csproj
<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">

  <PropertyGroup>
    <TargetFramework>net9.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <AssemblyName>RoutingLab</AssemblyName>
    <RootNamespace>RoutingLab</RootNamespace>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="9.0.4" />
    <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="9.0.4" PrivateAssets="all" />
  </ItemGroup>

</Project>
Program.csDownload file ↗
Program.cs
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using RoutingLab;

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

await builder.Build().RunAsync();
App.razorDownload file ↗
App.razor
@inject NavigationManager Navigation

@* The header sits outside the Router, so it stays on screen for every page.
   The next lesson moves it into a layout. *@
<header>
    <span class="brand">Routing Lab</span>
    <nav>
        @* NavLink adds class="active" while the address matches its href.
           Match="NavLinkMatch.All" needs the whole address, so Home is not active on other pages. *@
        <NavLink href="" Match="NavLinkMatch.All">Home</NavLink>
        @* The default is NavLinkMatch.Prefix: active on products, products/2 and products?sort=price. *@
        <NavLink href="products">Products</NavLink>
    </nav>
</header>

<main>
    @* The Router collects every component with @page in this assembly
       and renders the one whose route template matches the address. *@
    <Router AppAssembly="@typeof(App).Assembly">
        <Found Context="routeData">
            <RouteView RouteData="@routeData" />
            <FocusOnNavigate RouteData="@routeData" Selector="h1" />
        </Found>
        <NotFound>
            @* Shown when no template matches, for example products/abc. *@
            <PageTitle>Not found</PageTitle>
            <h1>Not found</h1>
            <p>No route template matches <code>/@Navigation.ToBaseRelativePath(Navigation.Uri)</code>.</p>
            <p>A constraint such as <code>{Id:int}</code> is part of matching, so a segment that is not a number ends up here.</p>
            <p><a href="">Back to Home</a></p>
        </NotFound>
    </Router>
</main>
_Imports.razorDownload file ↗
_Imports.razor
@using System.Net.Http
@using System.Net.Http.Json
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.JSInterop
@using RoutingLab
Pages/Home.razorDownload file ↗
Pages/Home.razor
@* One component can have several route templates. {Name?} is optional. *@
@page "/"
@page "/hello/{Name?}"
@inject NavigationManager Navigation

<PageTitle>Routing Lab</PageTitle>

<h1>@(Name is null ? "Routing Lab" : $"Hello, {Name}!")</h1>

<p class="address">
    Address: <code>/@Navigation.ToBaseRelativePath(Navigation.Uri)</code><br />
    Name parameter: <strong>@(Name ?? "null")</strong>
</p>

<h2>Try these addresses</h2>
<ul class="links">
    <li><a href="hello/Ada">hello/Ada</a> fills the optional Name segment.</li>
    <li><a href="hello">hello</a> leaves Name out, so it is null.</li>
    <li><a href="products">products</a> is a literal route.</li>
    <li><a href="products?sort=price">products?sort=price</a> adds a query string value.</li>
    <li><a href="products/2">products/2</a> matches the template products/{Id:int}.</li>
    <li><a href="products/abc">products/abc</a> fails the :int constraint, so the Router shows its NotFound content.</li>
    <li><a href="nowhere">nowhere</a> matches no template at all.</li>
</ul>

@code {
    // Filled from the {Name?} segment. On "/" the Router sets it to null.
    [Parameter]
    public string? Name { get; set; }
}
Pages/ProductDetails.razorDownload file ↗
Pages/ProductDetails.razor
@* {Id:int} matches only a segment that parses as an int. *@
@page "/products/{Id:int}"
@inject NavigationManager Navigation

<PageTitle>Product @Id</PageTitle>

@if (product is null)
{
    <h1>No product @Id</h1>
    <p>The address matched because @Id is a whole number. A route constraint checks the shape of a segment, not whether the item exists, so this page handles a missing product itself.</p>
}
else
{
    <h1>@product.Name</h1>
    <p>Product @product.Id costs $@product.Price.</p>
}

<div class="row">
    @if (Id > 1)
    {
        <a class="chip" href="products/@(Id - 1)">Previous</a>
    }
    <a class="chip" href="products/@(Id + 1)">Next</a>
    <button @onclick="BackToList">Back to the list, by price</button>
</div>

@code {
    // The Router converts the {Id:int} segment to int and assigns it here.
    // Route parameter names are not case-sensitive.
    [Parameter]
    public int Id { get; set; }

    private Products.Product? product;

    // Runs again when only Id changes, because the Router keeps this component.
    protected override void OnParametersSet() =>
        product = Products.Catalog.FirstOrDefault(item => item.Id == Id);

    private void BackToList() => Navigation.NavigateTo("products?sort=price");
}
Pages/Products.razorDownload file ↗
Pages/Products.razor
@page "/products"
@inject NavigationManager Navigation

<PageTitle>Products</PageTitle>

<h1>Products</h1>

<p>Sorted by <strong>@(ByPrice ? "price" : "name")</strong>. Query value: <code>sort=@(Sort ?? "null")</code></p>

<div class="row">
    <a class="chip @(ByPrice ? "" : "on")" href="products?sort=name">By name</a>
    <a class="chip @(ByPrice ? "on" : "")" href="products?sort=price">By price</a>
</div>

<ul class="list">
    @foreach (var product in Sorted)
    {
        <li>
            <a href="products/@product.Id">@product.Name</a>
            <span class="muted">$@product.Price</span>
        </li>
    }
</ul>

<h2>Open by number</h2>
<div class="row">
    <input type="number" @bind="target" aria-label="Product number" />
    <button class="primary" @onclick="Open">Open</button>
</div>
<p class="muted">The button calls Navigation.NavigateTo("products/@target"). Try 9 or 0 as well.</p>

@code {
    // Filled from ?sort=... in the address. A link that changes only the query
    // keeps this component and sets the value again.
    [SupplyParameterFromQuery]
    private string? Sort { get; set; }

    private int target = 3;

    private bool ByPrice => string.Equals(Sort, "price", StringComparison.OrdinalIgnoreCase);

    private IEnumerable<Product> Sorted =>
        ByPrice ? Catalog.OrderBy(product => product.Price) : Catalog.OrderBy(product => product.Name);

    // Code navigation: the same as tapping a link to products/{target}.
    private void Open() => Navigation.NavigateTo($"products/{target}");

    public sealed record Product(int Id, string Name, int Price);

    // A small catalog that ProductDetails.razor reads too.
    public static readonly IReadOnlyList<Product> Catalog =
    [
        new(1, "Desk lamp", 24),
        new(2, "Notebook", 6),
        new(3, "Backpack", 49),
        new(4, "Water bottle", 12)
    ];
}
wwwroot/css/app.cssDownload file ↗
wwwroot/css/app.css
:root {
    color-scheme: light dark;
    --accent: #6b4eff;
    --line: #d8d6e4;
}

body {
    margin: 0;
    font-family: -apple-system, system-ui, sans-serif;
    line-height: 1.5;
}

a, button, input, label {
    touch-action: manipulation;
}

a {
    color: var(--accent);
}

h1 {
    font-size: 1.7rem;
    margin: 0 0 12px;
}

h1:focus {
    outline: none;
}

h2 {
    font-size: 1.15rem;
    margin: 24px 0 8px;
}

code {
    font-size: 0.9em;
    overflow-wrap: anywhere;
}

.loading {
    padding: 32px 16px;
    color: #777;
}

.row {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 8px;
    margin: 12px 0;
}

input:not([type=checkbox]) {
    font: inherit;
    padding: 8px 10px;
    border: 1px solid var(--line);
    border-radius: 8px;
    min-width: 0;
    background: transparent;
    color: inherit;
}

button {
    font: inherit;
    padding: 8px 14px;
    border-radius: 8px;
    border: 1px solid var(--line);
    background: transparent;
    color: inherit;
}

button.primary {
    background: var(--accent);
    border-color: var(--accent);
    color: #fff;
}

button:disabled {
    opacity: 0.45;
}

.muted {
    color: #777;
}

#blazor-error-ui {
    display: none;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 12px 16px;
    background: #ffe8a3;
    color: #222;
}

header {
    position: sticky;
    top: 0;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 8px 16px;
    padding: 12px 16px;
    background: #1f1b3a;
    color: #fff;
}

.brand {
    font-weight: 700;
    margin-right: auto;
}

nav {
    display: flex;
    gap: 4px;
}

/* NavLink renders a plain <a>. It gets class="active" while its href matches. */
nav a {
    color: #d9d4ff;
    text-decoration: none;
    padding: 6px 10px;
    border-radius: 8px;
}

nav a.active {
    background: var(--accent);
    color: #fff;
}

main {
    padding: 20px 16px 40px;
    max-width: 720px;
    margin: 0 auto;
}

.address {
    padding: 10px 12px;
    border: 1px solid var(--line);
    border-radius: 10px;
}

.links {
    padding-left: 20px;
}

.links li {
    margin: 6px 0;
}

.chip {
    display: inline-block;
    padding: 6px 12px;
    border: 1px solid var(--line);
    border-radius: 999px;
    text-decoration: none;
}

.chip.on {
    background: var(--accent);
    border-color: var(--accent);
    color: #fff;
}

.list {
    list-style: none;
    padding: 0;
}

.list li {
    display: flex;
    justify-content: space-between;
    padding: 10px 0;
    border-bottom: 1px solid var(--line);
}

input[type=number] {
    width: 6em;
}
wwwroot/index.htmlDownload file ↗
wwwroot/index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Routing Lab</title>
    <base href="/" />
    <link rel="stylesheet" href="css/app.css" />
    <link rel="stylesheet" href="RoutingLab.styles.css" />
</head>
<body>
    <div id="app">
        <p class="loading">Starting .NET…</p>
    </div>

    <div id="blazor-error-ui">
        An unhandled error has occurred.
        <a href="." class="reload">Reload</a>
        <span class="dismiss">✕</span>
    </div>

    <script src="_framework/blazor.webassembly.js"></script>
</body>
</html>

Expected result

Home shows Address: / and Name parameter: null, with Home highlighted in the header. hello/Ada changes the heading to Hello, Ada! and shows Name parameter: Ada, and neither header link is highlighted; hello shows Name parameter: null. products?sort=price lists Notebook $6, Water bottle $12, Desk lamp $24 and Backpack $49 and shows sort=price; By name sorts the list alphabetically. products/2 shows Notebook with Previous and Next links, and the Products link stays highlighted. products/abc and nowhere show the Not found page with the address that failed. Open with 9 shows No product 9, because 9 is a valid int even though no product has that id.

The project runs in the SharpRune app and with the .NET 9 SDK. Open C# practice runs the separate portable exercise.

C# companion practice

Program.cs
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;

// The route templates that RoutingLab declares with @page.
string[] templates = ["/", "/hello/{Name?}", "/products", "/products/{Id:int}"];

string[] addresses = ["/", "/hello/Ada", "/hello", "/products?sort=price", "/products/2", "/products/abc", "/products/2/extra"];

foreach (var address in addresses)
{
    // The query string is not part of route matching. It is read separately.
    var parts = address.Split('?', 2);
    var query = parts.Length > 1 ? $" (query {parts[1]})" : "";
    var match = templates
        .Select(template => (Template: template, Values: Match(template, parts[0])))
        .FirstOrDefault(candidate => candidate.Values is not null);
    var result = match.Values is null
        ? "NotFound"
        : match.Template + string.Concat(match.Values.Select(pair => $" {pair.Key}={pair.Value ?? "null"}"));
    Console.WriteLine($"{address,-20} -> {result}{query}");
}

Console.WriteLine();
Console.WriteLine($"NavLink \"\" Prefix at products/2: {IsActive("", "products/2", prefix: true)}");
Console.WriteLine($"NavLink \"\" All at products/2: {IsActive("", "products/2", prefix: false)}");
Console.WriteLine($"NavLink \"products\" Prefix at products/2: {IsActive("products", "products/2", prefix: true)}");
Console.WriteLine($"NavLink \"products\" Prefix at productsale: {IsActive("products", "productsale", prefix: true)}");
Console.WriteLine($"NavLink \"products\" All at products?sort=price: {IsActive("products", "products?sort=price", prefix: false)}");

// Returns the route values, or null when the template does not match the path.
static Dictionary<string, string?>? Match(string template, string path)
{
    var expected = template.Split('/', StringSplitOptions.RemoveEmptyEntries);
    var actual = path.Split('/', StringSplitOptions.RemoveEmptyEntries);
    if (actual.Length > expected.Length) return null;
    var values = new Dictionary<string, string?>();
    for (var i = 0; i < expected.Length; i++)
    {
        var segment = expected[i];
        if (!segment.StartsWith('{'))
        {
            // A literal segment must be equal, ignoring case.
            if (i >= actual.Length || !string.Equals(segment, actual[i], StringComparison.OrdinalIgnoreCase)) return null;
            continue;
        }

        var inner = segment.Trim('{', '}');
        var optional = inner.EndsWith('?');
        var pieces = inner.TrimEnd('?').Split(':');
        var name = pieces[0];
        if (i >= actual.Length)
        {
            // A missing optional parameter is still supplied, as null.
            if (!optional) return null;
            values[name] = null;
            continue;
        }

        // The :int constraint is part of matching: "abc" makes this template fail.
        if (pieces.Length > 1 && pieces[1] == "int" && !int.TryParse(actual[i], NumberStyles.Integer, CultureInfo.InvariantCulture, out _)) return null;
        values[name] = actual[i];
    }

    return values;
}

// NavLink compares absolute addresses. Prefix also accepts longer addresses
// when a separator such as '/' or '?' follows the link's address.
static bool IsActive(string href, string current, bool prefix)
{
    var link = "https://app.example/" + href;
    var here = "https://app.example/" + current;
    if (string.Equals(here, link, StringComparison.OrdinalIgnoreCase)) return true;
    if (!prefix || here.Length <= link.Length || !here.StartsWith(link, StringComparison.OrdinalIgnoreCase)) return false;
    return !IsUnreserved(link[^1]) || !IsUnreserved(here[link.Length]);
}

static bool IsUnreserved(char c) => char.IsAsciiLetterOrDigit(c) || c is '-' or '.' or '_' or '~';
Open C# practice

C# practice output

/                    -> /
/hello/Ada           -> /hello/{Name?} Name=Ada
/hello               -> /hello/{Name?} Name=null
/products?sort=price -> /products (query sort=price)
/products/2          -> /products/{Id:int} Id=2
/products/abc        -> NotFound
/products/2/extra    -> NotFound

NavLink "" Prefix at products/2: True
NavLink "" All at products/2: False
NavLink "products" Prefix at products/2: True
NavLink "products" Prefix at productsale: False
NavLink "products" All at products?sort=price: False
Try this
A route constraint is part of matching, not validation: products/abc never reaches ProductDetails, but products/99 does, so the page must handle a missing product itself.

Further reading