Search code examples
routesrazorblazorblazor-server-side.net-8.0

Why is routing from one Razor component to another, both defined in the same RCL, does not work?


I have two minimal projects in my .NET 8 solution: a Blazor web server app, interactive server rendering, with Home.razor page, and a Razor class library with two components defined, Schedule and CodeView.

My Home.razor is:

@page "/"

@inject IServiceProvider ServiceProvider

<h3>Registered Routes</h3>
<ul>
    @foreach (var route in Routes)
    {
        <li>Route: @route End Route</li>
    }
</ul>

<PageTitle>Home</PageTitle>

<ScheduleView />

@code {
    private List<string> Routes { get; set; } = new();

    protected override void OnInitialized()
    {
        var routeDataSource = ServiceProvider.GetRequiredService<IEnumerable<EndpointDataSource>>();

        foreach (var r in routeDataSource)
        {
            foreach (var ep in r.Endpoints)
                Routes.Add(ep.ToString());
        }
    }
}

My ScheduleView.razor is:

@page "/scheduleview"
<ul class="nav nav-tabs">
    <li class="nav-item">
        <NavLink class="nav-link" activeClass="active" href="/codeview">PageWithForwardSlash</NavLink>
    </li>
    <li class="nav-item">
        <NavLink class="nav-link" activeClass="active" href="codeview">Logic</NavLink>
    </li>
</ul>

My CodeView.razor is:

@page "/codeview"

<h3>CodeView</h3>

@code {
}

My inclusion of the assembly for the routes is:

app.MapRazorComponents<App>()
    .AddInteractiveServerRenderMode()
    .AddAdditionalAssemblies(new[] { typeof(LuahSV.ScheduleView).Assembly }) ;

Results

  • ScheduleView is shown correctly in Home

Routes are outputing as:

Route: Blazor web static files End Route
Route: Blazor Opaque Redirection End Route
Route: /Error (/Error) End Route
Route: / (/) End Route
Route: /weather (/weather) End Route
Route: /codeview (/codeview) End Route
Route: /scheduleview (/scheduleview) End Route
Route: Microsoft.AspNetCore.Routing.RouteEndpoint End Route
Route: Microsoft.AspNetCore.Routing.RouteEndpoint End Route
Route: Microsoft.AspNetCore.Routing.RouteEndpoint End Route
Route: Microsoft.AspNetCore.Routing.RouteEndpoint End Route
Route: Microsoft.AspNetCore.Routing.RouteEndpoint End Route

Problem: when I click on the links in ScheduleView, I am getting an error "not found". Why?


Solution

  • app.MapRazorComponents<App>()
        .AddInteractiveServerRenderMode()
        .AddAdditionalAssemblies(new[] { typeof(LuahSV.ScheduleView).Assembly }) ;
    

    Adds the routes for server side rendering.

    You also need to add the routes to the Blazor Router in Routes.razor like this:

    <Router AppAssembly="typeof(Program).Assembly" AdditionalAssemblies="new[] { typeof(LuahSV.ScheduleView).Assembly">
        <Found Context="routeData">
            <RouteView RouteData="routeData" DefaultLayout="typeof(Layout.MainLayout)" />
            <FocusOnNavigate RouteData="routeData" Selector="h1" />
        </Found>
    </Router>