Search code examples
c#routesblazor.net-8.0razor-class-library

Blazor in .NET 8: Routing issue when load Page from Razor Class Library


I am currently encountering a routing issue in my new .NET 8 Blazor project. When attempting to navigate to a page defined in a Razor class library, I encounter a 404 error.

The Razor class library has already been properly referenced in the Blazor web application, and the Routes.razor file has been configured accordingly:

<Router AppAssembly="@typeof(Program).Assembly"
        AdditionalAssemblies="new[]{
                                    typeof(PostsPage).Assembly // Razor class library reference
                                   }">
    <Found Context="routeData">
        <RouteView RouteData="@routeData" DefaultLayout="@typeof(Layout.MainLayout)" />
        <FocusOnNavigate RouteData="@routeData" Selector="h1" />
    </Found>
    <NotFound>
        <LayoutView Layout="@typeof(Layout.MainLayout)">
            <p>Sorry, there's nothing at this address.</p>
        </LayoutView>
    </NotFound>
</Router>

I am facing the same issue after upgrading an existing .NET 7 project to .NET 8. According to the upgrade documentation, no additional configurations are required when transitioning from .NET 7 to .NET 8.

Does anyone have an idea about the problem and how to fix it?


Solution

  • I resolved the issue by call the "AddAdditionalAssemblies" method in the Program.cs class:

    app.MapRazorComponents<App>()
        .AddAdditionalAssemblies(typeof(PostsPage).Assembly) // the solution
        .AddInteractiveServerRenderMode();
    
    app.Run();
    

    For more information, you can take a look at this article.