DI IHttpContextAccessor.HttpContext is null after upgrade to 2.2.0
General
After upgrade aspnet core nuget packages from version 2.1.0 to 2.2.0 I've got issue IHttpContextAccessor.HttpContext unexpectedly became null during dependency injection.
I've investigated problem and found the cause of the problem was override HttpContext.TraceIdentifier in middleware. For 2.1.1 it was working well.
Details
Middleware:
public class DistinctTraceIdMiddleware
{
private readonly RequestDelegate _next; public DistinctTraceIdMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
// !!! OVERIDE cause of HttpContex = null !!!
context.TraceIdentifier = Guid.NewGuid().ToString("N");
await _next(context);
}
}
Resolving dependency in Startup.cs
public IServiceProvider ConfigureServices(IServiceCollection services)
{
ConfigureDefaultServices(services);
services.AddOptions();
services.AddTransient<ConfigurationResponse>(serviceProvider =>
{
var httpContextAccessor = serviceProvider.GetRequiredService<IHttpContextAccessor>();
if (httpContextAccessor?.HttpContext == null)
{
// !!! it should not be null but it is
throw new Exception("Why HttpContext is null?");
}
return new ConfigurationResponse();
});
return services.BuildServiceProvider();
}
I've created sample app to reproduce this issue.
Start solution and make http request on http:\\localhost:5000/api/configuration
DI IHttpContextAccessor.HttpContext is null after upgrade to 2.2.0
General
After upgrade aspnet core nuget packages from version 2.1.0 to 2.2.0 I've got issue IHttpContextAccessor.HttpContext unexpectedly became null during dependency injection. I've investigated problem and found the cause of the problem was override
HttpContext.TraceIdentifier
in middleware. For 2.1.1 it was working well.Details
Middleware:
Resolving dependency in Startup.cs
I've created sample app to reproduce this issue. Start solution and make http request on
http:\\localhost:5000/api/configuration
Source code with sample app: https://github.com/petttro/core2.2_HttpContext Also attached source code zip file here Sample.zip