How to Get HttpContext in ASP.NET Core (edit)
Access HttpContext in ASP.NET Core | Microsoft Docs
How to Get HttpContext ASP.NET Core (telerik.com)
Mock HTTPContext in ASP.NET Core Controller | TheCodeBuzz
Unit Testing .NET 5 Console Applications with Dependency Injection | Programming With Wolfgang
c# - Asp.net core session unit test - Stack Overflow
asp.net core - Returning null on httpContextAccessor.HttpContext - Stack Overflow
How to Access HttpContext in Service?
In ASP.NET Core, if we need to access the HttpContext in service, we can do so with the help of IHttpContextAccessor interface and its default implementation of HttpContextAccessor. It’s only necessary to add this dependency if we want to access HttpContext in service.
To use HttpContext in service we need to do following two steps:
Step 1: Register a dependency using the .NET Core built-in dependency injection container as below in Startup.cs class of ConfigureServices method:
Step 2: Next, inject the IHttpContextAccessor into the created service constructor and access the properties of HttpContext as below:
Now, you can access all the properties of HttpContext in service as shown in the above two steps.
You can also download this example from here.
Note: In .NET this was referenced as HttpContext.Current, but this is deprecated in ASP.NET Core (see here).
Conclusion
In this article, we discussed what HttpContext is and how to use it in a controller. After that we saw how to register and use it in service. If you have any suggestions or queries regarding this article, please leave a comment or contact me at one of the links in my bio.