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 #6080

Closed
petttro opened this Issue Dec 21, 2018 · 2 comments

Comments

Projects
None yet
3 participants
@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)
    {
        // !!! OVERRIDE 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();
}

To Reproduce

I've created sample app to reproduce this issue.
Start solution and make get 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

@Eilon

This comment has been minimized.

Copy link
Member

Eilon commented Dec 21, 2018

@davidfowl / @Tratcher - ideas on this?

@davidfowl

This comment has been minimized.

Copy link
Member

davidfowl commented Dec 21, 2018

Dupe of #5144. It's a bug in 2.2 that's being fixed in a patch. See the other issue for details.

@davidfowl davidfowl closed this Dec 21, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.