How to Access the HttpContext in a Class Library in ASP.NET Core?

3 minute read

INDEX

  • Context
  • Using the IHttpContextAccessor
  • Accessing HttpContext via Dependency Injection
  • Accessing HttpContext via Dependency Injection in a static class
  • Considerations

1. Context

In ASP.NET Core, the HTTP context cannot be accessed directly in the class library because it is a transient object that is available in the context of an HTTP request.

2. Using the IHttpContextAccessor

You can use the HTTPContext in a class library by injecting the IHttpContextAccessor to your class via the dependency injection from your startup class. Once you have injected the IHttpContextAccessor service into your class library, the HttpContext can be accessed from any method in your class.

3. Accessing HttpContext via Dependency Injection

Inject the HttpContextAccessor from the startup class and access it in the class library constructor.

3.1 Startup class

public void ConfigureServices(IServiceCollection services) {
    services.AddHttpContextAccessor();
}

3.2 Class library (user.cs)

public class User {
    private readonly IHttpContextAccessor _httpContextAccessor;

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

    public void GetUserList() {
        // Get the current HttpContext from the IHttpContextAccessor
        var httpContext = _httpContextAccessor.HttpContext;

        // Use the httpContext to access the stored items etc.
    }
}

4. Accessing HttpContext via Dependency Injection in static class

In a static class, the class is not instantiated and doesn’t create a new instance so it won’t call the constructor; hence, we can directly access the HttpContextAccessor within the static class.

4.1 Startup class

public void ConfigureServices(IServiceCollection services) {
    services.AddHttpContextAccessor();
}

4.2 Static class library (user.cs)

public static class User{

private HttpContext _httpContext => new HttpContextAccessor().HttpContext;

    public void GetUserList(){
        // You can access the HttpContext from _httpContext here.
    }
}

5. Considerations

  1. HttpContext is a huge object and accessing it can have a negative impact in the performance. Inject the IHttpContextAccessor when you need to access the HttpContext.
  2. Dispose of the IHttpContextAccessor when you are finished with it.

Thanks for reading the article about accessing the HttpContext in the class library via dependency injection. Please feel free to drop your comments below, and you can follow us on Twitter (@Codetoliveblog) to receive the latest updates from this blog.

Leave a comment