Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 41 ยท Routing and Layouts

Routing and Route Parameters

Learn Blazor routing with the @page directive, route parameters, optional values, constraints, catch-all routes and how the Router picks the best match for a URL.

In a Blazor app every page is a component, and a component becomes a page the moment you give it a route template. When the browser asks for /products/42, the framework has to decide which component to show and which pieces of the URL (42) to hand to it. That job belongs to the Router component, and the templates you write with the @page directive are the rules it works from.

This lesson covers the template syntax: literal segments, parameters, optional parameters, constraints, catch-all routes, multiple templates on one component and the tie-breaking rules. The real routing code needs the Blazor framework, so the Razor snippets are read-only. Our runnable examples are a small stand-in matcher in plain C# that follows the same ideas, so you can experiment with how templates match.

The @page directive

A component with at least one @page line is routable. The template starts with a slash and is compared with the URL path (the query string is ignored here, more on it in Query Strings and URL State).

RAZOR
@page "/about"

<h1>About us</h1>
<p>We write tutorials.</p>

You can stack several directives to give one component more than one address:

RAZOR
@page "/"
@page "/home"

<h1>Welcome</h1>

Matching is case-insensitive: /About and /about reach the same component. Under the hood, @page "/about" is compiled into a [Route("/about")] attribute on the component class. The Router scans the assemblies you list (usually the app assembly) at startup, collects every attribute and builds a route table.

Route parameters

Put a name in braces to capture a segment. The captured text goes into a component parameter with the same name (case-insensitive), which you declare with [Parameter].

RAZOR
@page "/products/{Id}"

<h1>Product @Id</h1>

@code {
    [Parameter]
    public string? Id { get; set; }
}

Visiting /products/42 sets Id to "42". Every captured value is text at first. To get a real number, add a constraint: {Id:int} converts the segment and also makes the route match only when the segment is a valid integer.

RAZOR
@page "/products/{Id:int}"

@code {
    [Parameter]
    public int Id { get; set; }
}

Now /products/abc does not match this page at all, and the router falls through to your "not found" content instead of crashing on a bad conversion.

Optional parameters and constraints

A trailing ? makes a parameter optional, and the matching component parameter must be nullable:

RAZOR
@page "/blog/{Year:int}/{Month:int?}"

Both /blog/2026 and /blog/2026/3 match. Built-in constraints include int, long, double, decimal, float, bool, guid, datetime, nonfile, and they work like the ones in ASP.NET Core endpoints (see Route Templates and Constraints). Constraints use invariant culture, so 1.5 is a valid double whatever the user's language.

Catch-all parameters

A parameter starting with * swallows the rest of the path, slashes included:

RAZOR
@page "/files/{*Path}"

/files/docs/2026/report.pdf gives Path = "docs/2026/report.pdf". Catch-all routes are handy for file browsers, wiki-style pages and a custom "not found" page.

How the router chooses

Several templates can match one URL. /products/new fits both /products/{Id} and /products/new. The router ranks the candidates with fixed rules:

  1. Literal segments beat parameters, so /products/new wins.
  2. Constrained parameters beat unconstrained ones.
  3. Optional and catch-all parameters rank last.
  4. If two routes tie, the framework throws an ambiguous match error at navigation time rather than guessing.
flowchart LR
    U["URL: /products/new"] --> R["Router"]
    R --> A["/products/new<br/>(literal)"]
    R --> B["/products/{Id:int}"]
    R --> C["/products/{Id}"]
    A -->|"wins"| P["New product page"]

Specific templates beat general ones, so you rarely need to order anything by hand.

A stand-in router you can run

The program below is not Blazor. It is a tiny matcher that splits a template and a URL into segments and applies literal, parameter, constraint and optional rules. It lets you see why a URL does or does not match.

C# Stand-in route matcher

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice that /products/new picks the literal route even though also matches, and /blog/2026/march fails because march is not an int.

Reading parameters inside a component

Route values arrive through the normal parameter system, so they are set before OnInitialized runs the first time. If the user navigates from /products/1 to /products/2, Blazor keeps the same component instance and only updates the parameter. That means loading data in OnInitialized shows stale data on the second page. Load in OnParametersSetAsync instead:

RAZOR
@page "/products/{Id:int}"
@inject IProductService Products

@if (product is null)
{
    <p>Loading...</p>
}
else
{
    <h1>@product.Name</h1>
}

@code {
    [Parameter] public int Id { get; set; }
    private Product? product;

    protected override async Task OnParametersSetAsync()
    {
        product = await Products.FindAsync(Id);
    }
}

This is one of the most common beginner bugs, and the next stand-in reproduces it without any framework.

C# Why OnParametersSet matters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The value loaded in OnInitialized is stuck on product 1 while the parameter moved to 2.

Do not parse NavigationManager.Uri by hand to find the current id. Declare a route parameter and let the router do it, so the value is typed, validated and kept up to date.

Not found

When no template matches, the Router renders whatever you place in its NotFound content (or, in .NET 10, a NotFoundPage you point at). You can also trigger it yourself from code with NavigationManager.NotFound(), which is how a page reports "no such product" after a database lookup. The page then sends a real 404 status when rendered on the server, which matters for search engines.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which template matches only when the last segment is a whole number?

    The :int constraint both converts the segment to an int and rejects URLs where it is not one.
  2. 2. A page has @page "/docs/{*Path}". What does /docs/a/b/c set Path to?

    A catch-all parameter takes the rest of the path, including slashes.
  3. 3. Navigating from /products/1 to /products/2 keeps the same component instance. Where should data be reloaded?

    OnInitialized runs once per instance, while OnParametersSet runs every time a parameter changes.
  4. 4. Both /products/new and /products/{Id} match /products/new. What happens?

    Literal segments rank higher than parameters, so the specific route is chosen.

Summary

  • @page "/path" turns a component into a page; stack several for multiple addresses.
  • captures a segment into a [Parameter]; :int, :guid and friends add type checks.
  • ? makes a parameter optional and * makes it a catch-all.
  • Literal segments beat constrained parameters, which beat plain ones.
  • Reload data in OnParametersSetAsync because the instance is reused.

Next: Navigation, NavLink and NavigationManager