.NET › Blazor (Server & WebAssembly)

How does Blazor handle routing, and what does the @page directive do?

Intermediate

Answer

The @page directive at the top of a component marks it as a routable page, associating it with a specific URL template; Blazor's Router component (registered in App.razor) scans the application's assemblies for all @page-decorated components at startup and matches incoming navigation requests to the appropriate component, similar conceptually to ASP.NET Core MVC routing but resolved entirely client-side (or via SignalR-relayed navigation events in Server mode).
@page "/products/{id:int}"

<h3>Product @Id</h3>

@code {
    [Parameter] public int Id { get; set; }
}
Real-world example A product-detail page uses a route parameter constraint {id:int} so navigating to /products/abc (non-numeric) doesn't match this component at all, falling through to a NotFound page instead.

Common follow-ups: How do you define a catch-all route parameter?;How does NavigationManager differ from anchor tags for programmatic navigation?