How-To: Delete a cookie in ASP.NET

Deleting a cookie from ASP.NET is something that trips up a lot of people (myself included when I first started ASP.NET coding). Here’s how:

What confused me originally is that HttpCookieCollection contains a Remove method. This doesn’t remove cookies from the user’s browser. It only removes the cookie entry from the local collection. What you have to do is force the user’s browser to delete the cookie itself. The way to do this is to add an expired cookie: the browser will then clean up the cookie itself.

void DeleteCookie( HttpContext context, string name )
{
  var cookie = context.Request.Cookies[name];

  if( cookie != null )
  {
    cookie.Expires = DateTime.Now.AddYears( -30 );

    context.Response.Cookies.Add( cookie );
  }
}

Note that I’m looking up the cookie in the request, but adding the expired cookie in the response.

2 Responses to “How-To: Delete a cookie in ASP.NET”

  1. It’s a common pitfall in most web development languages, including JavaScript. Even languages that implement ‘delete’ methods will ultimately set the cookie to expire.

    Other things to watch for are the number of cookies you set and the size of the data strings. All the browsers have differing limits, but IE generally allows 20 cookies of 4KB each. You won’t get any warnings if a cookie isn’t set or an old one disappears, so debugging can be a nightmare.

    Use cookies sparingly is probably the best advice.

    Incidentally, if you have variables that only retain state on the client side, there is an alternative to session cookies…
    http://www.optimalworks.net/blog/2008/web-development/javascript/javascript-nocookie-sessions

  2. Its ok but how will to delete cookie with the resposnse.Cookies.remove(“test”);

Leave a Reply