为什么 IHttpContextAccessor.HttpContext 有时为 null?

Jer*_*rey 5 c# httpcontext .net-core delegatinghandler

使用 .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();

Run Code Online (Sandbox Code Playgroud)

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

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;
}
Run Code Online (Sandbox Code Playgroud)

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