C#/ASP.NET: can't remove cookies with Domain property specified
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);
Alex
Updated on June 05, 2022Comments
-
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 over 12 yearsThank 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 over 12 yearsThanks for sharing your answer Alex. It helped me mate
-
Sunil Acharya about 9 yearsThanks for providing proper solution.
-
Dimitri about 4 yearsYou sir saved my day!!
-
The_Butcher over 2 yearsSAVED MY LIFE!!!!!!!!!!!!!!!!!!!!!!!!