35

I need to delete authentication cookie manually (Instead of using FormsAuthentication.SignOut whcih for some reasons does not work). I tried

System.Web.HttpContext.Request.Cookies.Remove(cookieName); // for example .ASPXAUTH
System.Web.HttpContext.Response.Cookies.Remove(cookieName); // for example .ASPXAUTH
FormsAuthentication.SignOut(); // I don't know why this one does not work

Neither of those command work. In fact Response cookies are empty and request cookie contains the cookie I want to delete when the following commands are executed it no longer contains the cookie I deleted but in browser the cookie still exists and I am able to do things that authorized users can even after signing out.

Dimitri
  • 2,798
  • 7
  • 39
  • 59
  • Does this answer your question? [How to remove all current domain cookies in MVC website?](https://stackoverflow.com/questions/6403978/how-to-remove-all-current-domain-cookies-in-mvc-website) – David Buck Jul 03 '20 at 21:35
  • "Calling the Remove method of the Cookies collection removes the cookie from the collection on the server side, so the cookie will not be sent to the client. However, the method does not remove the cookie from the client if it already exists there." [Source](https://learn.microsoft.com/en-us/previous-versions/ms178195(v=vs.140)?redirectedfrom=MSDN) – Asef Hossini Aug 31 '21 at 19:49

2 Answers2

84

Try:

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

More information on MSDN.

Asef Hossini
  • 655
  • 8
  • 11
Mateusz Rogulski
  • 7,357
  • 7
  • 44
  • 62
  • I used to set the authentication cookie manually but the name was different than the forms authentication cookie name. after I changed it FormsAuthentication.SignOut() actually worked. thanks anyways – Dimitri Nov 26 '13 at 14:01
5

c.Expires = DateTime.Now.AddDays(-1); This does not clear cookies instantly.

Use this: c.Expires = DateTime.Now.AddSeconds(1); This will clear cookies instantly.

SomoKRoceS
  • 2,934
  • 2
  • 19
  • 30
JBash
  • 51
  • 1
  • 1