Using Cookie in ASP.NET CORE

A cookie is a client-side state management technique which use to store a small amount of data on client end which is a browser.
A cookie is mostly used for recognizing Users who use application.

There are 2 types of Cookies.

  • Persistence:- Persistence Cookies are stored according to the time span given by the creator.
  • Non-Persistence:- Non-Persistence Cookies get expires as you close your 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.

For showing demo, I have added a New Controller with name Demo6 and Create ActionMethod in it.
In creating action method, we are going to create a cookie with name “DemoCookie” and we are going to set an expiration for a week and to add a cookie to the browser we are going to call Response.Cookies.Append().

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();
}

By Saineshwar Bageri

I am Microsoft MVP | C# Corner MVP | Code Project MVP | FULL STACK .NET Developer and working on .Net Web Technology (Asp.net, Asp.net Core,.Net Core, C#, Sqlserver, MVC, Windows, Console Application, javascript, jquery, json, ORM Dapper) and also a freelance developer.