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

10,891

Solution 1

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

Solution 2

I suspect you are setting Expires while the Response is on a subdomain...
Crosscheck: Can you try and set it from the domain itself and see if that works ?

According to http://msdn.microsoft.com/en-us/library/ms178195%28v=VS.100%29.aspx you can delete a cookie by:

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

Solution 3

Need to set domain and value with empty string. It does not work without value.

        var cookie = new HttpCookie(cookieName, string.Empty)
        {
            Expires = DateTime.Now.AddYears(-1),
            Domain = {YourDomain}
        };

        Response.Cookies.Add(cookie);
Share:
10,891
Alex
Author by

Alex

Updated on June 05, 2022

Comments

  • Alex
    Alex almost 2 years

    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

  • Alex
    Alex over 12 years
    Thank you for your answer. I set the cookies from the domain itself. I tried the very same example, and it works only in Opera.
  • DotNetInfo
    DotNetInfo over 12 years
    Thanks for sharing your answer Alex. It helped me mate
  • Sunil Acharya
    Sunil Acharya about 9 years
    Thanks for providing proper solution.
  • Dimitri
    Dimitri about 4 years
    You sir saved my day!!
  • The_Butcher
    The_Butcher over 2 years
    SAVED MY LIFE!!!!!!!!!!!!!!!!!!!!!!!!