Reputation: 15551
I created a cookie in my C# WebForms application, which I am testing on IE10 on Windows 7 64-bit.
The problem is that I cannot delete the cookie from the code behind. If I refresh the page or simply click on a hyperlink to goes back to the exact same page, the page can still read the cookie.
I have a popup control that in response to the user pressing the ok button, will do:
String key = "mycookiedata";
HttpCookie oCookie = null;
if (null != HttpContext.Current.Request.Cookies[key])
{
oCookie = HttpContext.Current.Request.Cookies[key];
oCookie.Expires = DateTime.Now.AddDays(-1);
HttpContext.Current.Response.Cookies.Set(oCookie);
}
Session.Remove(key);
Session.Abandon();
Session.Clear();
The code behind completes, and control goes back to the user. All seems fine until I refresh the page and find out that the cookie that I thought got deleted was not. I also tried out of sheer curiosity to close the browser window and reload the page in a new browser, and the cookie was still there. A user who logs out, should feel comfortable that they truly logged out and the cookie is gone.
Did I miss something in the code?
Upvotes: 2
Views: 4093
Reputation: 15551
Requesting a page, as in the first answer did not work. I tried several variants and nada.
I finally thought out the answer. In my EndCallback JavaScript event for the DevExpress callback panel for the ok button on the logout dialog, I implemented a call to a JavaScript function, Delete_Cookie. Having JavaScript delete the cookie worked!
There were two changes from the code behind, either one or both could have been what did the trick.
Here is a link to the article, whose Delete_Cookie code I used.
Upvotes: 0
Reputation: 22619
You cannot directly delete a cookie on a user's computer.
However, you can direct the user's browser to delete the cookie by setting the cookie's expiration date to a past date.
The next time a user makes a request to a page within the domain or path that set the cookie, the browser will determine that the cookie has expired and remove it.
Check this Delete a Cookie from MSDN
All you can do is you can make the cookie to be expired, by setting the past time
The below code will do that
if (Request.Cookies[key] != null)
{
HttpCookie myCookie = new HttpCookie(key);
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
Upvotes: 1