Alex Rivera | Logout

C#/ASP.NET: can't remove cookies with Domain property specified

Asked 2011-08-09T09:08:10.607
15

I have the following code in my login method:

Response.Cookies["cookie"].Value = "...";
Response.Cookies["cookie"].Domain = "domain.com";

This way the cookie is put into the main domain and all subdomains

However when I try to remove the cookies:

Response.Cookies["cookie"].Expires = DateTime.Now.AddYears(-1);

It doesn't work!

When I remove the 2 line of code where Domain property is specified, it works fine.

How can I solve this problem?

Thanks

Edit
Report

1 Answer

35

Okay, I figured that out.

When you remove a cookie with Domain property set, you need to set the very same property for the new fake cookie:

if (Request.Cookies["cookie"] != null)
{
    HttpCookie myCookie = new HttpCookie("cookie");
    myCookie.Expires = DateTime.Now.AddDays(-1d);
    myCookie.Domain = "domain.com"; // !!!!
    Response.Cookies.Add(myCookie);
}
answered 2011-08-14T15:53:10.253

Your Answer