Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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'

like image 861
NickG Avatar asked Aug 31 '25 01:08

NickG


1 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
like image 70
Farhad Zamani Avatar answered Sep 02 '25 14:09

Farhad Zamani