dotnet / core

.NET news, announcements, release notes, and more!
https://dot.net
MIT License
20.99k stars 4.91k forks source link

DI IHttpContextAccessor.HttpContext is null after upgrade to 2.2.0 #2179

Closed petttro closed 5 years ago

petttro commented 5 years ago

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

Source code with sample app: https://github.com/petttro/core2.2_HttpContext Also attached source code zip file here Sample.zip

MarcoRossignoli commented 5 years ago

Better move to https://github.com/aspnet/AspNetCore/issues

petttro commented 5 years ago

@MarcoRossignoli thank you for quick response Will do!

petttro commented 5 years ago

Moved here: https://github.com/aspnet/AspNetCore/issues/6080