How Routing in Blazor Works?
Table of Contents
Introduction
In Blazor, the route template provided to the accessible components makes the routing possible. A Blazor component (which is a Razor file with .razor extension) with @page directive, when compiled, generates a class. This generated class is given a RouteAttribute that specifies the route template. At runtime, the router looks for matching route templates with the requested URL in component classes with RouteAttribute.

In Fig 1, let’s think that there are three Razor files with @Page directive all getting compiled to generate corresponding class files. These class files at runtime have RouteAttributes given to them that specify the route template. If a request for a URL https://localhost:port/Counter is received, the fig shows that Razor file 3 will be rendered assuming that it has a template that matches the requested incoming URL.
Multiple Route Templates
We can apply more than one route templates to a single component like below:
@page "/Dialog" @page "/SampleDialog" <h1>Dialog Component </h1>
In the code above both the URL https://localhost:port/Dialog and https://localhost:port/SampleDialog will render the same Dialog Component.
Route parameters
The route templates provided in the @page directive can pass route parameters to the components. Corresponding component parameters are populated by the route parameters through the router.
Now let’s create a Header component in the Pages folder of the GetStartedBlazor that we have earlier created in our previous post here.
Header.Razor
@page "/header"
@page "/header/{message}"
<h1>Blazor is @Message</h1>
@code {
[Parameter]
public string Message { get; set; }
protected override void OnInitialized()
{
Message = Message ?? "fantastic";
}
}
Running the Application
With the header component as above if we run the application and browse to localhost:port/header we can see the message “Blazor is fantastic“

If we browse to browse to localhost:port/header/cool we are welcomed with the following rendering

If we again look above at the header component code, it will be clear that when we browse to localhost:port/header, the message property is null and so it is filled with a default message “fantastic” which comes from the code:
Message = Message ?? "fantastic";
In the second case when the route URL is : localhost:port/header/cool , the message value “cool” is obtained from the route parameter and the message “Blazor is cool” is printed on the browser.
YouTube Version
The YouTube Version of this post is available here
Follow Me Here