4

使用 .Net Core 2.2,我使用 HttpClient 调用 API,以及 Http 消息处理程序。消息处理程序注入IHttpContextAccessor,但该对象有时包含一个HttpContext为空的属性 - 我不明白为什么它会为空。

这是启动时的服务注册:

services.AddTransient<HttpClientTokenHandler>();

services.AddHttpClient("client", c =>
    {
        c.BaseAddress = new Uri(options.ApiUrl.TrimEnd('/') + '/');
    }).AddHttpMessageHandler<HttpClientTokenHandler>();

services.AddHttpContextAccessor();

以及 HttpContext 有时为空的令牌处理程序实现。

public HttpClientTokenHandler(IHttpContextAccessor context)
{
    _context = context;
}

protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{    
    var access_token = await _context.HttpContext.GetTokenAsync(Constants.TokenTypes.AccessToken);

    if (!string.IsNullOrEmpty(access_token))
    {
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", access_token);
    }
    var response = await base.SendAsync(request, cancellationToken);
    return response;
}

_context.HttpContext当它只是被注入时,什么可能导致它为空?

4

0 回答 0