Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
petttro opened this issue Dec 21, 2018 · 3 comments
Closed

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

petttro opened this issue Dec 21, 2018 · 3 comments

Comments

@petttro
Copy link

petttro commented Dec 21, 2018

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
Copy link
Member

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

@petttro
Copy link
Author

petttro commented Dec 21, 2018

@MarcoRossignoli thank you for quick response
Will do!

@petttro
Copy link
Author

petttro commented Dec 21, 2018

Moved here: dotnet/aspnetcore#6080

@petttro petttro closed this as completed Dec 21, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants