I am trying to setup named HttpClient in Blazor WASM. Problem is that I need to call async method in order to get JWT.
builder.Services.AddHttpClient("auth", async c =>
{
// access the DI container
var serviceProvider = builder.Services.BuildServiceProvider();
// Find the HttpContextAccessor service
var localStorageService = serviceProvider.GetService<ILocalStorageService>();
// Get the bearer token.
if (localStorageService == null) return;
var jwt = await localStorageService.GetJwtAsync();
Console.WriteLine("JWT "+jwt);
if (jwt != null)
{
c.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwt);
}
}
);
This doesn't work since parameter c cannot be async function.
Next I tried something like this
builder.Services.AddHttpClient("auth", c =>
{
// access the DI container
var serviceProvider = builder.Services.BuildServiceProvider();
// Find the HttpContextAccessor service
var localStorageService = serviceProvider.GetService<ILocalStorageService>();
// Get the bearer token.
if (localStorageService == null) return;
var jwt = localStorageService.GetJwtAsync().Result;
Console.WriteLine("JWT "+jwt);
if (jwt != null)
{
c.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwt);
}
}
);
In this case I get an error
Unhandled exception rendering component: Cannot wait on monitors on this runtime
because I am using .Result in WASM and it is blocking the main thread.
Any ideas is this possible to implement and how?