Skip to content

Blazor SSR Navigate does not work inside try/catch block #57311

Closed as not planned
@mrpmorris

Description

@mrpmorris

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

In a Blazor SSR app, NavigationManager.NavigateTo always throws an exception.

The problem with this approach is when debugging async await methods in Visual Studio the debugger does not stop to show this exception, so the developer is unaware.

It is therefore likely the developer will include the call to NavigateTo within a try block, and then navigation fails...

    private async Task Save()
    {
        try
        {
            await Task.CompletedTask; // A task that may throw an exception
            NavigationManager.NavigateTo("/success");
        }
        catch 
        {
            // Log the exception and show an error to the user
        }
    }

Expected Behavior

It should not throw an exception.

I should be able to write the same code as I would for Server or WASM Blazor apps.

Steps To Reproduce

// VS will stop and show the exception
private void Example1()
{
  NavigationManager.NavigateTo("/eggs");
}

// But I need some async code in my save handler
// VS will NOT stop and show the exception
private async Task Example2()
{
  await Task.CompletedTask; // My complex task
  NavigationManager.NavigateTo("/eggs");
}

// My own async code might throw an exception, so I
// wrap it in a try/catch to tell the user the operation failed
// This will successfully execute the task, but never navigate
private async Task Example3()
{
  ErrorMessage = null;
  try
  {
      await Task.CompletedTask; // My complex task
      NavigationManager.NavigateTo("/eggs");
   }
  catch
  {
    ErrorMessage = "The operation failed";
  }
}

Exceptions (if any)

Microsoft.AspNetCore.Components.NavigationException

.NET Version

8.0.303

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions