How ToT2 Dark_1200x303
In this article, we will discuss what HttpContext is and how to use it in a controller, plus how to register and use it in service.

Today we are going to learn about HttpContext in .NET Core. This article covers the following topics:

  • What is HttpContext?
  • How to access HttpContext in controller?
  • How to access HttpContext in service?
  • Conclusion

What is HttpContext?

It holds the current information about the Http request. It contains the information like authorization, authentication, request, response, session, items, users, formOptions, etc. Every HTTP request creates a new object of HttpContext with current information.

How to Access HttpContext in Controller?

Let’s see how to access the HttpContext in a controller. Controllers expose the ControllerBase.HttpContext property so we can directly access the HttpContext properties for the current Http request. The best practice is to always access HttpContext through the DI with a default implementation of HttpContextAccessor.

Example: The example below shows accessing the HttpContext in a controller GET action method:

[HttpGet("/getDetails")]
public string GetDetails()
{
   var result = "Method - " + HttpContext.Request.Method + 
                " Path - " + HttpContext.Request.Path;
   return result;
}

Output: Method - GET Path - /getdetails

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>();
}

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;
        }
    }
}

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.

“Learn It, Share it.”


jeetendra
About the Author

Jeetendra Gund

Jeetendra Gund is a C# Corner MVP as well as the Chapter Leader of C# Corner Pune Chapter. He holds a master’s degree in Computer Science and has worked on several different domains. He has spent six years in grooming his knowledge about Microsoft Technologies and has been sharing his experiences on technologies such as C#.Net, MVC.Net, SQL Server, Entity Framework, AngularJS, JavaScript, HTML, and .NET Static Code Analysis. He is a regular speaker at C# Corner on Microsoft Technologies. Find him: C# Corner, LinkedIn, or Twitter.

Related Posts

Comments

Comments are disabled in preview mode.