Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IHttpContextAccessor HttpContext are always null

Tags:

asp.net-core

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;

        .....
    }
like image 645
Iris Avatar asked Jun 03 '17 10:06

Iris


1 Answers

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.

like image 67
Set Avatar answered Oct 25 '22 23:10

Set