26

I am working on a MVC website, and in my logout link I want to remove all the current domain cookies.

I tried this:

this.ControllerContext.HttpContext.Response.Cookies.Clear();

and this:

Response.Cookies.Clear();

but both didn't work and the cookies still there.

tereško
  • 58,060
  • 25
  • 98
  • 150
Amr Elgarhy
  • 66,568
  • 69
  • 184
  • 301
  • possible duplicate of [How do you clear cookies using asp.net mvc 3 and c#?](http://stackoverflow.com/questions/5122404/how-do-you-clear-cookies-using-asp-net-mvc-3-and-c) – Jakub Konecki Jun 19 '11 at 17:32
  • 1
    I think that guy was only trying to delete one cookie. This guy wants to delete them all – Swift Jun 19 '11 at 17:34
  • Yes, I want to clear all cookies, not just one, deleting one cookie was fine, I am asking about deleting all domain cookies. – Amr Elgarhy Jun 19 '11 at 17:36

3 Answers3

60

How about this?

string[] myCookies = Request.Cookies.AllKeys;
foreach (string cookie in myCookies)
{
  Response.Cookies[cookie].Expires = DateTime.Now.AddDays(-1);
}
Swift
  • 13,118
  • 5
  • 56
  • 80
  • 1
    @Swift, this deletes all the cookies for the main domain like "www.example.com". What if you want to delete all the cookies along with sub domains like "abc.example.com" or "mobile.example.com" ?? Any idea. – Naphstor Aug 15 '17 at 14:18
1

What about this ?

    if (Request.Cookies["cookie"] != null)
    {
        HttpCookie myCookie = new HttpCookie("cookie");
        myCookie.Expires = DateTime.Now.AddDays(-1d);
        Response.Cookies.Remove(myCookie);
    }
Sunil Acharya
  • 1,153
  • 5
  • 22
  • 39
0
myCookie.Expires = DateTime.Now.AddDays(-1d);

This does not clear the cookies instantly.

You can use:

myCookie.Expires = DateTime.Now.AddSeconds(1);

To clear cookies instantly

David Buck
  • 3,752
  • 35
  • 31
  • 35
JBash
  • 51
  • 1
  • 1