In this article, we will learn how to use Cookies in our .NET Core Web applications. I assume that your web application is already created.
In ASP.NET MVC, we accessed cookies from httpcontext but in .NET Core, we need to use IHttpContextAccessor interface which falls under “Microsoft.AspNetCore.Http” namespace
Now, We can use the cookies by following the below codes.
First, we need to add an IHttpContextAccessor in the ConfigureServices method of Startup class.
services.AddHttpContextAccessor();
To Set Cookie
CookieOptions option = new CookieOptions
{
Expires = DateTime.Now.AddMinutes(1)
};
Response.Cookies.Append("Key Name", "Value", option);
To Get/Read Cookie
We can get/read cookies in two ways
var cookieValue = Request.Cookies`"Key Name"`;
private readonly IHttpContextAccessor _httpContextAccessor;
public HomeController(IHttpContextAccessor httpContextAccessor)
{
this._httpContextAccessor = httpContextAccessor;
}
var value = _httpContextAccessor.HttpContext.Request.Cookies`"Key Name"`;
Below are available Cookie Options: