Iris
Iris

Reputation: 1476

IHttpContextAccessor HttpContext are always null

I have problem when I'm trying to get httpcontext from IHttpContextAccessor field is always null.

There is my startup.cs

    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc();
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        .....

        // This is always null
        var httpContext = app.ApplicationServices.GetService<IHttpContextAccessor>().HttpContext;

        .....
    }

Upvotes: 21

Views: 28959

Answers (3)

zed101
zed101

Reputation: 323

In my case, this error appeared for a while during debugging when I commented JwtAuth attribute on my controller. So, make sure you're sending jwt token with that attribute applied.

Upvotes: 0

Zaha
Zaha

Reputation: 946

In my case the problem was I forget await in the begining of stack, explicity in my constructor action method

NOTE: Using net core 5.0 with IHttpContextAccessor

So the problem was in the next code...

[HttpPost]
public async Task AnyAction()
{
    await service.MethodReturningTask(); //await was not
}

DETAIL: The method "MethodReturingTask()" had some await in their implementations, and after that await the stack disapear together with httpContextAccessor.HttpContext propertie (to null)

Upvotes: 1

Set
Set

Reputation: 49769

You always will have null HttpContext in Configure method.

This method is used to specify how the ASP.NET application will respond to HTTP requests and calls once on Application start, not for each HTTP request. That's why there is nothing, what could be populated to HttpContext.

You need to pass IHttpContextAccessor in your service classes and call IHttpContextAccessor.HttpContext during request processing. You may look into "similar" situation with getting HTTP context in this SO post.

Upvotes: 27

Related Questions