How to get HttpContext.Current in ASP.NET Core

By FoxLearn 12/27/2024 8:31:40 AM   25
In ASP.NET Core, `HttpContext.Current` was removed. Instead, `HttpContext` is injected into services, controllers, and middleware via dependency injection, and can be accessed using the `IHttpContextAccessor` interface.

Accessing HttpContext in Controllers

In ASP.NET Core, the HttpContext is accessible directly through the HttpContext property on any controller. The equivalent of using HttpContext.Current in your original code would be to pass HttpContext to methods like so:

public class HomeController : Controller
{
    public IActionResult Index()
    {
        MyMethod(HttpContext);

        // Additional code...
    }
}

public void MyMethod(Microsoft.AspNetCore.Http.HttpContext context)
{
    var host = $"{context.Request.Scheme}://{context.Request.Host}";

    // Additional code...
}

Accessing HttpContext in Middleware

When writing custom middleware in ASP.NET Core, the current request's HttpContext is automatically passed into the Invoke method.

public Invoke(HttpContext context)
{
    // Perform operations with the current HTTP context...
}

Using IHttpContextAccessor

For scenarios where you need to access the HttpContext in classes that aren't directly linked to a controller or middleware (e.g., in shared services), you can use the IHttpContextAccessor interface.

To use it, inject IHttpContextAccessor into your constructor:

public class MyService
{
    private readonly IHttpContextAccessor _httpContextAccessor;

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

    public void SomeMethod()
    {
        var context = _httpContextAccessor.HttpContext;
        // Access HttpContext here
    }
}

Since IHttpContextAccessor is not always registered by default, you should ensure it’s added to the service container in ConfigureServices:

public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpContextAccessor();
    // If using .NET Core version < 2.2, use this:
    // services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    // Other service registrations...
}

To replace HttpContext.Current in ASP.NET Core, you use the IHttpContextAccessor service, which gives you access to the current HttpContext. You need to register IHttpContextAccessor in the ConfigureServices method, and then you can inject it wherever you need access to the HttpContext.