How to delete cookies on an ASP.NET website How to delete cookies on an ASP.NET website asp.net asp.net

How to delete cookies on an ASP.NET website


Try something like that:

if (Request.Cookies["userId"] != null){    Response.Cookies["userId"].Expires = DateTime.Now.AddDays(-1);   }

But it also makes sense to use

Session.Abandon();

besides in many scenarios.


No, Cookies can be cleaned only by setting the Expiry date for each of them.

if (Request.Cookies["UserSettings"] != null){    HttpCookie myCookie = new HttpCookie("UserSettings");    myCookie.Expires = DateTime.Now.AddDays(-1d);    Response.Cookies.Add(myCookie);}

At the moment of Session.Clear():

  • All the key-value pairs from Session collection are removed. Session_End event is not happen.

If you use this method during logout, you should also use the Session.Abandon method to Session_End event:

  • Cookie with Session ID (if your application uses cookies for session id store, which is by default) is deleted


This is what I use:

    private void ExpireAllCookies()    {        if (HttpContext.Current != null)        {            int cookieCount = HttpContext.Current.Request.Cookies.Count;            for (var i = 0; i < cookieCount; i++)            {                var cookie = HttpContext.Current.Request.Cookies[i];                if (cookie != null)                {                    var expiredCookie = new HttpCookie(cookie.Name) {                        Expires = DateTime.Now.AddDays(-1),                        Domain = cookie.Domain                    };                    HttpContext.Current.Response.Cookies.Add(expiredCookie); // overwrite it                }            }            // clear cookies server side            HttpContext.Current.Request.Cookies.Clear();        }    }