Defining routes

To define a route we simply add a @page declaration at the top of any component.

@page "/"

<h1>Hello, world!</h1>

Welcome to your new app.

If we open the generated source code for this view (in obj\Debug\netcoreapp3.0\Razor\Pages\Index.razor.g.cs) we see the @page directive compiled to the following code.

[Microsoft.AspNetCore.Components.LayoutAttribute(typeof(MainLayout))]
[Microsoft.AspNetCore.Components.RouteAttribute("/")]
public class Index : Microsoft.AspNetCore.Components.ComponentBase
{
}

The @page directive generates a RouteAttribute on the component’s class. During start-up, Blazor scans for classes decorated with RouteAttribute and builds its route definitions accordingly.

Route discovery

Route discovery is performed automatically by Blazor in its default project template. If we look inside the App.razor file we’ll see the use of a Router component.

… other code …
    <Router AppAssembly="typeof(Startup).Assembly">
        … other code …
    </Router>
… other code … 

The Router component scans all classes within the specified assembly that implement IComponent, it then reflects over the class to see if it is decorated with any RouteAttribute attributes. For each RouteAttribute it finds, it parses its URL template string and adds a relationship from the URL to the component into its internal route table.

This means a single component may be decorated with zero, one, or many RouteAttribute attributes (@page declarations). A component with zero cannot be reached via a URL, whereas a component with multiple can be reached via any of the URL templates it specifies.

@page "/"
@page "/greeting"
@page "/HelloWorld"
@page "/hello-world"

<h1>Hello, world!</h1>

Pages may also be defined in Component libraries.