Wednesday, July 4, 2018

Access HttpContext using dependency injection in .net core mvc (c# , .NET CORE)


Add singleton service of IHttpContextAccessor in Startup.cs. 

 //IHttpContextAccessor 
services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor,Microsoft.AspNetCore.Http.HttpContextAccessor>();

Then you can resolve IHttpContextAccessor using constructor ( or by using IServiceProvider )
            
private static IHttpContextAccessor _httpContextAccessor;
// constructor
public MyClass(IHttpContextAccessor httpContextAccessor)
{
    _httpContextAccessor = httpContextAccessor;
}

or using IServiceProvider

   _httpContextAccessor = serviceProvider.GetService<IHttpContextAccessor>();


Then, you can access the HttpContext ( or eg. set string in session) as :

 _httpContextAccessor.HttpContext.Session.SetString("key", "value");


Click the link to know about dependency injection using IServiceProvider