In this article I will explain with an example, how to use HttpContext in ASP.Net Core (.Net Core 6).
Microsoft has permanently removed HttpContext.Current property from .Net Core and introduced a new interface IHttpContextAccessor for ASP.Net Core 6.
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.
Program class Configuration
Inside the Program.cs file, the IHttpContextAccessor interface service is added to the builder object using the AddHttpContextAccessor method.
var builder = WebApplication.CreateBuilder(args);
//Enabling MVC
builder.Services.AddControllersWithViews();
builder.Services.AddHttpContextAccessor();
var app = builder.Build();
//Configuring Routes
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
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