Blazor WASM 和 Refit 代币
Blazor WASM and Refit token
我在我的 blazor wasm 应用程序中使用改装,我想在 AuthorizationHeaderValueGetter 中设置令牌,我连接的 api 不是用 .net 编写的。但我已经在 program.cs
中注册了改装
builder.Services.AddRefitClient<IApi>(settings).ConfigureHttpClient(c =>
{
c.BaseAddress = new Uri("Address");
})
我必须为此创建一个 DelegatingHandler 吗?
public class AuthHeaderHandler : DelegatingHandler
{
private readonly ILocalStorageService _localStorageService;
public AuthHeaderHandler(ILocalStorageService localStorageService)
{
_localStorageService = localStorageService;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var auth = request.Headers.Authorization;
if (auth != null)
{
if (await _localStorageService.ContainKeyAsync("Token"))
{
string token = await _localStorageService.GetItemAsync<string>("Token");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
}
}
return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
}
}
我在我的 blazor wasm 应用程序中使用改装,我想在 AuthorizationHeaderValueGetter 中设置令牌,我连接的 api 不是用 .net 编写的。但我已经在 program.cs
中注册了改装builder.Services.AddRefitClient<IApi>(settings).ConfigureHttpClient(c =>
{
c.BaseAddress = new Uri("Address");
})
我必须为此创建一个 DelegatingHandler 吗?
public class AuthHeaderHandler : DelegatingHandler
{
private readonly ILocalStorageService _localStorageService;
public AuthHeaderHandler(ILocalStorageService localStorageService)
{
_localStorageService = localStorageService;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var auth = request.Headers.Authorization;
if (auth != null)
{
if (await _localStorageService.ContainKeyAsync("Token"))
{
string token = await _localStorageService.GetItemAsync<string>("Token");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
}
}
return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
}
}