Cookies are a client-side state management technique used to store a small amount of data directly on the client’s browser. They are commonly used for identifying users and maintaining state across multiple requests in web applications.
Types of Cookies
There are two types of cookies:
1. Persistent Cookies
Persistent cookies are stored in the browser for a specified time duration set by the developer. These cookies remain available even after the browser is closed and reopened, until their expiration time is reached.
2. Non-Persistent (Session) Cookies
Non-persistent cookies, also known as session cookies, are stored only for the duration of the browser session. These cookies are automatically deleted when the user closes the browser.
We are going to see a short demo of how to create a cookie and read the view from the cookie in ASP.NET Core.
Demo: Creating and Reading Cookies in ASP.NET Core
Let’s go through a quick demonstration on how to create a cookie and read its value in an ASP.NET Core application.
Step 1: Add a Controller
Create a new controller named Demo6Controller.
Creating Cookie
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
namespace WebApplication2.Controllers
{
public class Demo6Controller : Controller
{
public IActionResult Create()
{
string key = "DemoCookie";
string value = DateTime.Now.ToString();
CookieOptions options = new CookieOptions();
options.Expires = DateTime.Now.AddDays(7);
Response.Cookies.Append(key, value, options);
return View();
}
}
}
To see cookie which is added in the browser I am using Firefox.
Now to read value which is stored in cookie we are going to add another action method with name Read.
Reading Value from Cookie
For reading value from the cookie, we are going to use Request.Cookies Collection to this collection we need to pass key (“DemoCookie“).
public IActionResult Read()
{
string key = "DemoCookie";
var CookieValue = Request.Cookies[key];
return View();
}
Removing Cookie
After creating cookie and reading value from cookie last part was how to remove or delete the cookie from the browser for doing that, we need to set the expiration of cookie to a past date and update a cookie.
If you see below code, we have set past date as DateTime.Now.AddDays(-1); and added cookie to browser.
public IActionResult Remove()
{
string key = "DemoCookie";
string value = DateTime.Now.ToString();
CookieOptions options = new CookieOptions();
options.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Append(key, value, options);
return View();
}
