COOKIE IN ASP.NET CORE

Below sample C# code demonstrated on how to create and set 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  browser

There are 2 types of Cookies.

  • Persistence:- Persistence Cookies are stored according to the time span mentioned by user
  • Non-Persistence:- Non-Persistence Cookies get expires when 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.

I have added Home Controller with name 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().


 public IActionResult Create()
        {

            string key = "DemoCookie";
            string value = "Yogesh";

            CookieOptions options = new CookieOptions();
            options.Expires = DateTime.Now.AddDays(7);
            Response.Cookies.Append(key, value, options);

            return View("Index");
        }

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




Now to read value which is stored in cookie we are going to add another action method with name Read.

Reading Value from Cookie

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











Comments

Popular posts from this blog

How to Integrate SB Admin 2 Template in Asp.net Mvc Application

Send mail when Rss news is published using Logic Apps - Azure portal

environment setup for Angular Application