Course contentsShow
← C#
Lesson 1351 of 1,90812. Modern Frontend with Razor and BlazorFree lesson

Custom Routing and Middleware

Implement custom logic for page navigation and request interception.

In this lesson, you will learn how to intercept and redirect navigation requests before they reach your Blazor components, allowing you to centralize control over page access.

Custom Routing Logic

In Blazor, the NavigationManager service is your primary tool for handling URL changes. While the built-in router handles standard page discovery, you can implement custom routing logic by subscribing to the LocationChanged event. This is particularly useful for global redirections or logging.

For example, you can inject the NavigationManager into your MainLayout.razor to intercept requests based on custom business rules:

@inject NavigationManager NavManager
@implements IDisposable

protected override void OnInitialized()
{
    NavManager.LocationChanged += HandleLocationChanged;
}

private void HandleLocationChanged(object sender, LocationChangedEventArgs e)
{
    // Custom logic: Redirect if user attempts to access restricted paths
    if (e.Location.Contains("/admin") && !UserIsAdmin)
    {
        NavManager.NavigateTo("/unauthorized");
    }
}

public void Dispose() => NavManager.LocationChanged -= HandleLocationChanged;

Middleware Concepts

In the context of Blazor, "middleware" is often implemented at the ASP.NET Core hosting level before the Blazor circuit even starts. Since Blazor Server and WebAssembly operate within the browser, you use the Program.cs file to define request interception for the initial page load.

If you need to ensure a user has specific metadata before a page renders, you can register a custom DelegatingHandler or use ASP.NET Core middleware to inspect the HttpContext. By the time the Blazor component renders, your middleware has already validated the request context, ensuring that your application state remains consistent with your security or routing policies.

These techniques allow you to move navigation concerns out of individual components and into a centralized, maintainable layer. By coupling event-driven navigation listeners with request-level interception, you create a robust navigation system that enforces your application's flow regardless of user interaction.

Key Takeaway: Custom routing in Blazor relies on subscribing to the NavigationManager.LocationChanged event for client-side flow control, while ASP.NET Core middleware handles initial request interception before the Blazor application initializes.