Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 41 ยท Routing and Layouts

Route Constraints and Catch-All Routes in Blazor

Restrict Blazor route parameters with constraints like int and guid, accept optional values, capture whole paths with catch-all routes and build a custom not-found page.

A route template such as /products/{Id} matches any text in the last segment: /products/42, but also /products/banana. If Id is an int, the second URL would fail while converting the value, so Blazor offers route constraints that decide at routing time whether a page should match at all. A URL that fails every template ends up on the not-found page instead of crashing a component.

This lesson covers the built-in constraints, optional parameters, catch-all parameters and the not-found content of the router. The Razor snippets are real Blazor syntax and read-only; the runnable examples are small C# stand-ins that mimic how a router tests a template against a path, so you can see the matching rules in action.

Constraints

A constraint follows the parameter name after a colon:

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

<h1>Product @Id</h1>

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

Now /products/42 matches, while /products/banana does not match this page and falls through to other routes or to the not-found page. Because the router already converted the text, the parameter can be a real int instead of a string you parse yourself.

Blazor supports these constraints: bool, datetime, decimal, double, float, guid, int and long. They are culture-invariant: 1.5 is a valid double, 1,5 is not, no matter the user's language.

Template Matches Does not match
/orders/{Id:int} /orders/7 /orders/seven
/events/{Day:datetime} /events/2026-03-01 /events/tomorrow
/files/{Key:guid} a valid GUID /files/report
/switch/{On:bool} /switch/true /switch/yes

A constraint only checks the shape of the value. It does not check that product 42 exists. Do that in OnInitializedAsync and show a not-found state yourself when the lookup fails.

Several routes on one page

A page can have multiple @page lines. This is the classic way to make a parameter optional: one route without it and one with it.

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

<h1>@(Year is null ? "All posts" : $"Posts from {Year}")</h1>

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

Two different pages must never claim the same template; the router reports an "ambiguous routes" error, and a literal segment (/blog/archive) wins over a parameter segment (/blog/{Year}).

Catch-all parameters

A parameter written with a star captures the rest of the path, including slashes:

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

<h1>Doc page: @Path</h1>

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

/docs/guides/setup/windows gives Path = "guides/setup/windows". Catch-all parameters must be string and must come last in the template. They are the right tool for file browsers, wikis and "docs" areas where the depth varies. Treat the value as user input: never use it directly to open a file on disk.

A router you can run

The real router is generated from your @page templates. This stand-in does the same job with a tiny matcher so you can test templates against paths. It supports literals, , {Name:int} and {*Rest}.

C# Stand-in: matching templates against paths

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 matched the literal template even though /products/{Id:int} exists, and that /products/banana ended up as NotFound. The real router has more rules, but the principle is the same: the most specific match wins.

The not-found page

When no template matches, the router renders its NotFound content (newer templates can also redirect to a dedicated not-found page). A classic Routes.razor looks like this:

RAZOR
<Router AppAssembly="typeof(Program).Assembly">
    <Found Context="routeData">
        <RouteView RouteData="routeData" DefaultLayout="typeof(Layout.MainLayout)" />
        <FocusOnNavigate RouteData="routeData" Selector="h1" />
    </Found>
    <NotFound>
        <PageTitle>Not found</PageTitle>
        <LayoutView Layout="typeof(Layout.MainLayout)">
            <h1>Sorry, nothing lives here.</h1>
            <p>Check the address or go back to the <a href="/">home page</a>.</p>
        </LayoutView>
    </NotFound>
</Router>

A component that loads data should show the same kind of page when a record is missing. The exact API depends on your Blazor version, so check the template of your project; the idea is to stop rendering the page and show shared not-found content instead of an empty screen.

A not-found guard you can run

C# Stand-in: validating a route value and a missing record

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.

Common mistakes

  • Writing the constraint in upper case. {Id:INT} is not valid; constraints are lower case.
  • Putting a catch-all in the middle. {*Path} must be the last segment.
  • Relying on constraints for security. A guid constraint rejects report, but it does not prove the user may see that file. Authorize separately (see Authentication and Authorization).
  • Duplicate templates. Two pages with /about stop the app with an ambiguity error.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens when the URL is /orders/seven and the only template is /orders/{Id:int}?

    A failed constraint means the route does not match, so the router continues to other routes and finally to NotFound.
  2. 2. Which template captures the rest of the path, including slashes?

    A star before the parameter name makes it a catch-all. It must be a string and the last segment.
  3. 3. A constraint like :guid proves that...

    Constraints only check the format of the segment. Existence and permissions need separate checks.
  4. 4. How do you make a parameter optional in a way that works in every Blazor version?

    Multiple @page lines on one component give you both routes, and the parameter is nullable.

Summary

  • Constraints such as :int, :guid, :datetime and :bool make a template match only when the segment has the right shape.
  • Use several @page lines for optional parameters; a literal segment beats a parameter segment.
  • {*Path} captures the rest of the path as a string and must be last.
  • Non-matching URLs reach the router's not-found content; missing records need your own not-found handling.
  • Constraints validate shape, never permissions or existence.

Next: Dependency Injection in Blazor