# HttPContextAccessor in ASP.NET Core

While working with ASP.NET Core web applications, developers often need `HttpContext` to access the properties associated with request and response.

A `HttpContext` object encapsulates all such properties for example request path, request method, query string parameters, response status and code, response content type, etc.

### Why HttPContextAccessor?

Accessing `HttpContext` inside framework-level APIs like controllers, middlewares, Razor pages, and Razor views are fairly simple where an `HttpContext` object is exposed and can be used directly.

A real-world application consists of more than framework-level APIs and builds with various components. For example, consider an N-Layer architecture application or a [clean architecture](https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html) application where an application has more than one library that interacts with each other.

Here comes `HttPContextAccessor` into picture which helps to access `HttpContext` inside non-framework constructs. We will understand this with an example below.

for this article, we will take an example of an ASP.NET Core web API application that is built using 3 layers.

below is the project structure for this application :

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1705337281603/5c0268cc-1ab6-4081-8510-07a9ba51dd15.png align="left")

* DemoWebApi - Web API project
    
* DataAccess - responsible for data access i.e. database connection
    
* Application - application's business logic layer
    

Now consider a requirement where we need to access the current `HttpContext` inside the Application layer or Data Access layer. This could be anything like accessing the current logged-in user or user claims etc.

In such a scenario, `HttpContext` is not directly accessible or cannot be injected as a dependency. So we utilize the `HttPContextAccessor` to achieve the above-mentioned objective.

### How to use HttPContextAccessor?

To understand the use of `HttPContextAccessor` , we are going to create a sample application that has 3 layers as demonstrated above. We have a requirement where we need to log the request path. for demonstration purposes, we would access the `HttpContext` request's path inside the `Application` project and will log it inside the `DataAccess` project.

The code for this demo can be found in the [HttpContextAccessorDemo](https://github.com/dkj468/HttpContextAccesorDemo) Github repo.

* Add dependency to inject `HttpContextAccessor` in `Program.cs` file.
    
    ```csharp
    builder.Services.AddHttpContextAccessor();
    ```
    
* Create a service that needs the `HttpContextAccessor`
    
    ```csharp
    public interface IRequestPathAccessor {
        string GetRequestPath();
    }
    public class RequestPathAccessor : IRequestPathAccessor {
        private readonly IHttpContextAccessor _httpContextAccessor;
        public RequestPathAccessor(IHttpContextAccessor httpContextAccessor){
            _httpContextAccessor = httpContextAccessor;
        }
        public string GetRequestPath(){
            return _httpContextAccessor.HttpContext.Request.Path;
        }
    }
    ```
    
* Finally, inject RequestPathAccessor as a service into the dependency container to be used inside some other project. (Inside Program.cs file)
    
    ```csharp
    builder.Services.AddHttpContextAccessor();
    builder.Services.AddScoped<IRequestPathAccessor, RequestPathAccessor>();
    ```
    
* Service to log the request path (DataAccess project)
    
    ```csharp
        public interface IRepoService {
            void LogRequestPath();
        }
    
        public class RepoService : IRepoService{
            private readonly IRequestPathAccessor _userAccessor;
            public RepoService(DataContext context,  IRequestPathAccessor userAccessor){
                _userAccessor = userAccessor;
            }
            public void LogRequestPath(){
                // get path 
                var path = _userAccessor.GetRequestPath();
                Console.WriteLine(path);
            }
        }
    ```
    
    In this way, `HttPContextAccessor` could be used to access the current context.
    
    Thanks
    

### Resources

* [Access HttpContext in ASP.NET Core | Microsoft Learn](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-context?view=aspnetcore-8.0)
