In this article I will explain with an example, how to use HttpContext in ASP.Net Core (.Net Core 5).
Microsoft has permanently removed HttpContext.Current property from .Net Core and introduced a new interface IHttpContextAccessor for ASP.Net Core (.Net Core 5).
What is IHttpContextAccessor
The IHttpContextAccessor is an interface for .Net Core for accessing HttpContext property.
This interface needs to be injected as dependency in the Controller and then later used throughout the Controller.
This interface allows us to access the HttpContext property which in turn provides access to Request collection and also the Response property.
Startup class Configuration
You will need to add the AddHttpContextAccessor function in the ConfigureServices method of Startup class as shown below.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddHttpContextAccessor();
}
Namespaces
You will need to import the following namespace.
using Microsoft.AspNetCore.Http;
Using IHttpContextAccessor
In the below example, a public property of type IHttpContextAccessor is defined.
Then, the IHttpContextAccessor is injected in the Controller's Constructor using the process of Dependency Injection and assigned to the private property Accessor and later used to access the HttpContext properties.
public class HomeController : Controller
{
private IHttpContextAccessor Accessor { get; set; }
public HomeController(IHttpContextAccessor _accessor)
{
this.Accessor = _accessor;
}
public IActionResult Index()
{
HttpContext context = this.Accessor.HttpContext;
return View();
}
}
Screenshot
Downloads