Saving, reading and removing values from Cookies in ASP.NET MVC

This short tutorial is about how we can store any information inside the cookie and read from it.
1. Create a new cookie

HttpCookie cookie = new HttpCookie("cookieMonster");
cookie.Value = ”Hi, I am cookie monster and I am not addicted to cookies”
HttpContext.Response.Cookies.Add(cookie);

2. Read value from cookie.

string cookieValue = HttpContext.Request.Cookies["cookieMonster"].Value;

3. To remove cookie we have to use this simple trick. We will find the cookie and change expiration date to yesterday.

if (HttpContext.Request.Cookies.AllKeys.Contains("cookieMonster"))
            {
                var cookie = HttpContext.Request.Cookies["cookieMonster"];
                cookie.Expires = DateTime.Now.AddDays(-1);
                HttpContext.Response.Cookies.Add(cookie);
            }


Let me know if you find a better approach!

Adam Bielecki.

Comments