MudBlazor / Templates

Ready to use Blazor Templates in different styles and layout with all the basic setup already done for MudBlazor.
MIT License
745 stars 165 forks source link

Open Dialog from DelegatingHandler not working #484

Open NGame1 opened 2 weeks ago

NGame1 commented 2 weeks ago

Hi everyone, I want to handle 401 status code globally to open a Dialog to login user. So I tried to Add related services into my program

builder.Services.AddScoped<LoginModalService>();
builder.Services.AddScoped<AuthenticationHttpMessageHandler>();

builder.Services.AddHttpClient<IMyService, MyService>(client =>
{
    client.BaseAddress = new Uri(builder.Configuration["ApiBaseUrl"] ?? "https://localhost:7000/");
})
.AddHttpMessageHandler<AuthenticationHttpMessageHandler>();

And my AuthenticationHttpMessageHandler is simply opens a dialog

public class AuthenticationHttpMessageHandler : DelegatingHandler
{
    private readonly LoginModalService _loginModalService;

    public AuthenticationHttpMessageHandler(LoginModalService loginModalService)
    {
        _loginModalService = loginModalService;
    }

    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var response = await base.SendAsync(request, cancellationToken);

        if (response.StatusCode == HttpStatusCode.Unauthorized)
        {
            await _loginModalService.ShowLoginModal();
        }

        return response;
    }
}

public class LoginModalService(IDialogService dialogService)
{
    private readonly IDialogService _dialogService = dialogService;

    public event Action? OnLogin;

    public async Task ShowLoginModal()
    {
        var dialog = await _dialogService.ShowAsync<TestModal>();
        var result = await dialog.Result;

        if (result?.Canceled == false)
        {
            OnLogin?.Invoke();
        }
    }
}

If I try to Inject IDialogService and Show a dialog on OnAfterRenderAsync method it simply works, but if I try to call an API and it invoke the ShowAsync in LoginModalService witch is calling from AuthenticationHttpMessageHandler it will not working. Any workaround or fix?

My Project is .NET 8.0 and I'm using default Mudblazor Server template for my app. dotnet new mudblazor --interactivity Server --name MyApplication --all-interactive