12

How to Get HttpContext ASP.NET Core

 3 years ago
source link: https://www.telerik.com/blogs/how-to-get-httpcontext-asp-net-core
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
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.”


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK