5

Using .Net Core 2.2, I'm using HttpClient to call an API, along with an Http Message Handler. The message handler injects IHttpContextAccessor, but that object sometimes contains an HttpContext property that is null - I can't understand why that would ever be null.

Here's the service registration in startup:

services.AddTransient<HttpClientTokenHandler>();

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

services.AddHttpContextAccessor();

And the token handler implementation where HttpContext is sometimes 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;
}

What could cause _context.HttpContext to be null, when it's simply being injected?

0 Answers0