asp.net-corenavigationblazorclient.net-8.0

Blazor Web App NavigationManager in Client -> Exception_WasThrown


I was creating a Blazor Web App using VS2022. Here is the project overview: Blazor Web App project overview

When using the NavigationManager in the code section of the Client project I get an Exception_WasThrown error: Exception

Here is the Home.razor content in BlazorApp.Client:

@page "/"
@inject NavigationManager NavigationManager

<PageTitle>Home</PageTitle>

<h1>Hello, world!</h1>

Welcome to your new app.

@code {
    protected override void OnInitialized()
    {
        NavigationManager.NavigateTo("/weather");
    }
}

I already added this:

app.MapRazorComponents<App>()
        .AddInteractiveWebAssemblyRenderMode()
        .AddAdditionalAssemblies(typeof(BlazorApp1.Client._Imports).Assembly);

to Program.cs in the BlazorApp project and I have updated my Routes.razor in the Client project as follows:

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

Anything I am missing here?

Thanks!

I was trying adding the assembly to the Project.cs as well as the Route.razor according to https://learn.microsoft.com/en-us/aspnet/core/blazor/fundamentals/routing?view=aspnetcore-8.0


Solution

  • Get confirmation from OP, using OnAfterRender instead of OnInitialized could solve the issue. Based on my test, when the exception occurred, I can press F5 to continue to run the application and the navigation will complete finally, so that I'm afraid the exception is somewhat similar to first-chance exception due to the conflict between initialization and rendering. So that using OnAfterRender can avoid this conflict.

    protected override void OnAfterRender(bool firstRender)
    {
        if (firstRender){
             NavigationManager.NavigateTo("/weather");
        }
    }