简体   繁体   中英

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'

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

You should do this with filters. Not within your constructor. This is not thread safe: https://learn.microsoft.com/en-us/as.net/core/fundamentals/http-context?view=as.netcore-6.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM