我在服务器端Blazor应用程序中有一个IdentityServer4 / WebAPI设置和一个键入的HttpClient。我想在向API发出请求时动态添加访问令牌。但是HttpContext
和AuthenticationStateProvider
都无法在AddHttpClient
方法或AddHttpMessageHandler
中访问。
这在本地可用,但在服务器httpContextAccessor
上运行为空:
services.AddHttpClient<IMyClient, MyClient>((serviceProvider, client) =>
{
var httpContextAccessor = serviceProvider.GetService<IHttpContextAccessor>();
var accessToken = await httpContextAccessor.HttpContext.GetTokenAsync("access_token");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
}).AddHttpMessageHandler<MyApiBearerTokenHandler>();
尝试访问AuthenticationStateProvider
services.AddHttpClient<IMyClient, MyClient>((serviceProvider, client) =>
{
var authStateProvider = serviceProvider.GetService<AuthenticationStateProvider>();
}).AddHttpMessageHandler<MyApiBearerTokenHandler>();
引发以下错误:
'无法解析范围服务 'Microsoft.AspNetCore.Components.Authorization.AuthenticationStateProvider' 来自根提供商。”
如何将访问令牌放入AddHttpClient
?我完全走错了路吗?