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

Tips & tricks for unit testing in .NET Core 3: Mocking IHttpContextAccessor – Anthony Giretti's .NET blog

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:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    //IHttpContextAccessor register
    services.AddHttpContextAccessor();
    services.AddTransient<IUserService, UserService>();
}
C#

Step 2: Next, inject the IHttpContextAccessor into the created service constructor and access the properties of HttpContext as below:

namespace Get_HttpContext_ASP.NET_Core
{
    using Microsoft.AspNetCore.Http;

    public class UserService : IUserService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;

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

        public string GetLoginUserName()
        {
            return _httpContextAccessor.HttpContext.User.Identity.Name;
        }
    }
}
C#

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.