dotnet / aspnetcore

ASP.NET Core is a cross-platform .NET framework for building modern cloud-based web applications on Windows, Mac, or Linux.
https://asp.net
MIT License
35.37k stars 9.99k forks source link

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

Closed mrpmorris closed 2 months ago

mrpmorris commented 2 months ago

Is there an existing issue for this?

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

MackinnonBuck commented 2 months ago

Thanks for reaching out. This is by design - NavigationException is intended to be caught by the framework to be handled as a redirect. Our guidance is to not catch that exception. We currently have #55685 tracking an alternative approach to initiating redirects.