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;
.....
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With