views:

96

answers:

4

how to remove cookies from browser in asp.net c#

A: 

The easiest way to delete a cookie is to set its expiration date to a time of the past.
For example,
Set-Cookie: cookieName=; expires=Wed, 12 May 2010 06:33:04 GMT;
It works because at the time i'm posting, Wed, 12 May 2010 06:33:04 GMT is the http-timestamp, which will never happen again.

ItzWarty
+2  A: 

Here's how.

if (Request.Cookies["MyCookie"] != null)
{
    HttpCookie myCookie = new HttpCookie("MyCookie");
    myCookie.Expires = DateTime.Now.AddDays(-1d);
    Response.Cookies.Add(myCookie);
}
Sohnee
+1, but mention the source: http://msdn.microsoft.com/en-us/library/ms178195(v=VS.90).aspx
orip
A: 

Below is code where you can delete all cookies :

void Page_Load()
    {
        string[] cookies = Request.Cookies.AllKeys;
        foreach (string cookie in cookies)
        {
            BulletedList1.Items.Add("Deleting " + cookie);
            Response.Cookies[cookie].Expires = DateTime.Now.AddDays(-1);
        }
    }

for more detail about cookies : http://msdn.microsoft.com/en-us/library/ms178194.aspx

Pranay Rana
A: 

Helper based on http://msdn.microsoft.com/en-us/library/ms178195.aspx :

public static void DeleteCookie(
  HttpRequest request, HttpResponse response, string name)
{
  if (request.Cookies[name] == null) return;
  var cookie = new HttpCookie(name) {Expires = DateTime.Now.AddDays(-1d)};
  response.Cookies.Add(cookie);
}
orip