I am using the Visual Studio 2019
and .Net Core 3.0.0-preview-7
with the standard Blazor Client, Server and Shared templates.
In the application our server side WebApi application will always require a JWT token to be present in the header for authorization.
From looking at the following
Make HTTP requests using IHttpClientFactory in ASP.NET Core
I created the following handler;
public class JwtTokenHeaderHandler : DelegatingHandler
{
private readonly ILocalStorageService _localStorage;
public JwtTokenHeaderHandler(ILocalStorageService localStorage)
{
_localStorage = localStorage;
}
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
if (!request.Headers.Contains("bearer"))
{
var savedToken = await _localStorage.GetItemAsync<string>("authToken");
if (!string.IsNullOrWhiteSpace(savedToken))
{
request.Headers.Add("bearer", savedToken);
}
}
return await base.SendAsync(request, cancellationToken);
}
}
Where I use Blazored.LocalStorage
to get the saved token from localstorage and add it to the header.
Now, at this point I am not sure what to do as if I add the following to the Blazor.Client
Startup.cs
;
services.AddTransient<JwtTokenHeaderHandler>();
services.AddHttpClient("JwtTokenHandler")
.AddHttpMessageHandler<JwtTokenHeaderHandler>();
I get the error message;
'IServiceCollection' does not contain a definition for 'AddHttpClient' and no accessible extension method 'AddHttpClient' accepting a first argument of type 'IServiceCollection' could be found (are you missing a using directive or an assembly reference?)
Can anyone direct me to what I am doing wrong here?