Didsbury Design Blog

How to: Create and Delete a cookie in ASP.NET C#

April 29th, 2010

I thought I would do a quick post about Creating and more importantly Deleting cookies in ASP.NET as it’s not quite as obvious as it may seem with the misleading .Remove() method which doesnt do as you would expect.

I hope this helps someone get started with cookies if your just getting started with the .NET framework.

Creating a cookie

This is a basic example of how to create a cookie in ASP.NET C#

//Create a new cookie, passing the name into the constructor
HttpCookie cookie = new HttpCookie("MyCookie");

//Set the cookies value
cookie.Value = "CookieValue";

//Set the cookie to expire in 1 day
cookie.Expires = DateTime.Now.AddDays(1);

//Add the cookie
Response.Cookies.Add(cookie);

Deleting a cookie

When deleting a cookie all you need to do is amend the HttpCookie object so it has an expiry date in the past, then re-save the cookie to push the new value to the client.

// Clear cookie Info
            if(Request.Cookies["MyCookie"]!=null){

                HttpCookie cookie = Request.Cookies["MyCookie"];
                cookie.Expires = DateTime.Now.AddDays(-1);

                Response.Cookies.Add(cookie);
            }
Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay