Inject the context into a random class
If you’re not in a controller, you can still access the HttpContext by injecting IHttpContextAccessor.
The following example demonstrates how to inject the context into a random class:
public class SomeOtherClass
{
private readonly IHttpContextAccessor _httpContextAccessor;
public SomeOtherClass(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public void TestSet()
{
_httpContextAccessor.HttpContext.Session.SetString("Test", "Ben Rules!");
}
public void TestGet()
{
var message = _httpContextAccessor.HttpContext.Session.GetString("Test");
}
}
The above approach needs you to register a dependency using the built-in dependency injection container. The dependency injection container supplies the IHttpContextAccessor
to any classes that declare it as a dependency in their constructors:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddHttpContextAccessor();
.....
}