Search code examples
c#cookiessubdomain

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


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


Solution

  • 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);
    }