How To Use Cookie In ASP.NET Core Application

Introduction

This article is for those who want to learn how to store data into browser cookies using Asp.net core MVC Application. If you want to implement it you can create a sample web application using the Asp.net Core MVC web application 

Let's get started.

A cookie is basically a small piece of data that the server sends to the user's web browser. The browser may store it and send back it with the later request to the same server. Typically it's used to tell the browser if two requests came from the same browser.

Types of cookie 

Persistent cookie

A cookie that has not to have expired time which is called a persistent cookie 

Non-Persistent cookie

Cookie which has expired time is called a Non-persistent cookie 

Adding cookie to the browser

First, add methods inside the Home controller. I have created an action method as CreateCookie and I have added key as DemoCookie. After that I have stored string value as Yogesh so we can store this value in the client browser 

public IActionResult CreateCookie() {
    string key = "DemoCookie:;
    string value = Yogesh;
    cookieOptions obj = new CookieOptions();
    obj.Expires = DateTime.Now.AddDays(7);
    Response.Cookie.Append(key, value, options);
    return view();
}

To see the cookie which is added in the browser I am using Google Chrome.

How To Use Cookie In ASP.NET Core Application

Now we will see how to retrieve data from cookies, here I have created Action Method ReadData that is used to retrieve data from cookies.

public IActionResult Read Data() {
    string key = "DemoCookie";
    var CookieValue = Request.Cookies[key];
    return View();
}

How To Use Cookie In ASP.NET Core Application

Now we will see how to delete data that is stored in cookies, here I have created the Action method Delete to perform the Delete operation on the cookie.

public IActionResult Delete() {
    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();
}

Summary 

In this article, we have seen how to store data into cookies and retrieve and delete data from cookies.

Hope you guys like it ... 

Happy Coding .