Search code examples
c#blazordotnet-httpclient

Call unauthorized controller in Blazor scoped HttpClient


So in Blazor Web Assembly (with ASP.NET Scoped) we have this great new HttpClient:

builder.Services.AddHttpClient(
    "ServerAPI", 
    client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
    .AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();

builder.Services
    .AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("ServerAPI"));

But I have some controller, that by design is supposed to be called before user authentication, thus I don't have token yet.

@inject HttpClient HttpClient;
// (... irrelevant razor code)
await HttpClient.PostAsync("UnauthorizedController", someData);

and I got exception: Microsoft.AspNetCore.Components.WebAssembly.Authentication.AccessTokenNotAvailableException

And the question is, how should those unauthorized request be handled?


Solution

  • You don't need to have only one HttpClient in your app.

    Register 2 named clients:

    builder.Services.AddHttpClient(
        "ServerAPI", 
        client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
        .AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();
    
    builder.Services.AddHttpClient(
        "UnauthorizedServerAPI", 
        client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress));
    

    In your blazor component inject IHttpClientFactory and create client when needed:

    @inject IHttpClientFactory _clientFactory;
    // (... irrelevant razor code)
    
    var client = _httpClientFactory.CreateClient("UnauthorizedServerAPI");
    await client.PostAsync("UnauthorizedController", someData);