38

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.

2
  • Does this answer your question? How to remove all current domain cookies in MVC website? Commented Jul 3, 2020 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 Commented Aug 31, 2021 at 19:49

2 Answers 2

87

Try:

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

More information on MSDN.

Sign up to request clarification or add additional context in comments.

1 Comment

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
7

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.