Introduction to Blazor Routing
Blazor's routing system allows you to define how your application's UI responds to URL changes. It enables users to navigate between different components or views within your Blazor application, providing a seamless single-page application (SPA) experience.
This document covers the fundamental concepts and advanced features of Blazor routing.
Core Routing Concepts
Blazor routing relies on matching the current URL to route templates defined in your components. When a match is found, the corresponding component is rendered.
- Route Template: A string that defines the URL pattern to match.
- Route Matching: The process of comparing the current URL with available route templates.
- Component Rendering: Displaying the component associated with the matched route.
Defining Routes
You define routes for your Blazor components using the @page directive.
For example, to make a component accessible at the root path /, you would add:
@page "/"
<h1>Welcome!</h1>
This is your home page.
To define a route for a specific path:
@page "/counter"
<h1>Counter</h1>
<p>Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
}
Route Parameters
Route parameters allow you to capture dynamic values from the URL and pass them as arguments to your component.
Define route parameters by enclosing them in curly braces {} in the route template. These parameters must correspond to public properties in your component marked with the [Parameter] attribute.
@page "/products/{productId:int}"
<h1>Product Details</h1>
Displaying details for Product ID: @ProductId
@code {
[Parameter]
public int ProductId { get; set; }
}
In this example, if the URL is /products/123, ProductId will be set to 123.
Note: Blazor supports various route parameter types, including int, string, guid, etc. You can also specify parameter constraints.
Route Constraints
Route constraints enable you to specify the type or format of route parameters. This helps in more precise route matching.
Common constraints include int, long, guid, alpha (alphabetic characters), decimal, datetime, and bool.
@page "/users/{username:alpha}"
<h1>User Profile</h1>
Viewing profile for user: @Username
@code {
[Parameter]
public string Username { get; set; }
}
The :alpha constraint ensures that the username parameter only matches if it contains alphabetic characters.
Catch-all Routes
Catch-all routes allow you to match any path that hasn't been matched by more specific routes. They are defined using the {**catchAll} syntax.
@page "/{**slug}"
<h1>Not Found</h1>
The requested path "@Slug" was not found.
@code {
[Parameter]
public string Slug { get; set; }
}
This component will be rendered if no other route matches the URL. The slug parameter will capture the entire remaining path.
Programmatic Navigation
You can navigate programmatically within your Blazor application using the NavigationManager service.
Inject the NavigationManager into your component and use its NavigateTo method.
@inject NavigationManager NavigationManager
<h1>Navigation Example</h1>
<button class="btn btn-primary" @onclick="GoToCounter">Go to Counter</button>
@code {
private void GoToCounter()
{
NavigationManager.NavigateTo("/counter");
}
}
Tip: The NavigateTo method has an overload that accepts a boolean parameter ForceLoad. Setting it to true forces a full page reload, bypassing Blazor's client-side navigation.
NavLink Component
The NavLink component is a specialized link that automatically applies an 'active' CSS class when its href matches the current URL.
<NavLink href="/" Match="NavLinkMatch.All">Home</NavLink>
<NavLink href="/counter">Counter</NavLink>
NavLinkMatch.All ensures the link is active only when the URL exactly matches. Other options include NavLinkMatch.Prefix (default) which is active if the URL starts with the href.
Layout Routes
Layouts provide a way to share common UI elements (like headers, footers, and navigation) across multiple components. Routes can be associated with layouts.
@layout MyLayout
@page "/about"
<h1>About Us</h1>
<p>Information about our company.</p>
Here, the About component will be rendered within the structure defined by MyLayout.razor.
Route Groups
Route groups allow you to associate a common route prefix with a set of components. This is useful for organizing related pages.
@* In a file like Routes.razor *@
@using MyWebApp.Pages.Admin
<RouteView RouteData="@RouteData" DefaultLayout="@typeof(MainLayout)" />
@code {
[CascadingParameter]
private RouteData RouteData { get; set; }
}
@* In Pages/Admin/Index.razor *@
@page "/admin"
<h1>Admin Dashboard</h1>
@* In Pages/Admin/Users.razor *@
@page "/admin/users"
<h1>Manage Users</h1>
In this setup, /admin and /admin/users are handled by components within the Pages/Admin folder.
Authorization
Blazor integrates seamlessly with ASP.NET Core's authorization system. You can protect specific routes using the [Authorize] attribute.
@page "/settings"
@attribute [Authorize]
<h1>User Settings</h1>
<p>This page is only accessible to authenticated users.</p>
Components marked with [Authorize] will only be accessible to users who meet the authorization requirements.