How to delete cookies on an ASP.NET website

Viewed 261194

In my website when the user clicks on the "Logout" button, the Logout.aspx page loads with code Session.Clear().

In ASP.NET/C#, does this clear all cookies? Or is there any other code that needs to be added to remove all of the cookies of my website?

11 Answers

You should never store password as a cookie. To delete a cookie, you really just need to modify and expire it. You can't really delete it, ie, remove it from the user's disk.

Here is a sample:

HttpCookie aCookie;
    string cookieName;
    int limit = Request.Cookies.Count;
    for (int i=0; i<limit; i++)
    {
        cookieName = Request.Cookies[i].Name;
        aCookie = new HttpCookie(cookieName);
        aCookie.Expires = DateTime.Now.AddDays(-1); // make it expire yesterday
        Response.Cookies.Add(aCookie); // overwrite it
    }

Response.Cookies["UserSettings"].Expires = DateTime.Now.AddDays(-1)

You have to set the expiration date to delete cookies

Request.Cookies[yourCookie]?.Expires.Equals(DateTime.Now.AddYears(-1));

This won't throw an exception if the cookie doesn't exist.

I strongly preferer this if anyone like it.

string COOKIE_NAME = "COOCKIE NAME"

if (HttpContext.Request.Cookies.AllKeys.Contains(COOKIE_NAME))
        {
            HttpCookie Cookie = HttpContext.Request.Cookies[COOKIE_NAME];
            engagementIdCookie.Expires = DateTime.Now.AddDays(-1);
            Response.Cookies.Add(Cookie);
        }
Related