How do you access HttpContext in the constructor of a Controller in .NET Core 3?

Viewed 2595

How do you access HttpContext in the constructor of a Controller in .NET Core 3.1?

It always seems to be null in the constructor, but is available in the actual methods. This was possible in MVC 4 and this has come up while trying to port the project to .NET Core.

If I try and use the HttpContextAccessor through DI, this fails with an exception:

InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Http.HttpContextAccessor' while attempting to activate 'MyProject.Controllers.UsersController'

2 Answers

You can use the IHttpContextAccessor for access to HttpContext.

for access HttpContext you must add services.AddHttpContextAccessor() to ConfigureService method

services.AddHttpContextAccessor();

and get IHttpContextAccessor from Dependency Injection in constructor

private readonly IHttpContextAccessor _httpContextAccessor;

public UsersController(IHttpContextAccessor httpContextAccessor)
{
    _httpContextAccessor = httpContextAccessor;
}

access to HttpContext

_httpContextAccessor.HttpContext
Related