Reputation: 1591
On pageload of Home page, I have set a cookie like this:-
if (abc == true)
{
HttpCookie cookie = new HttpCookie("Administrator");
cookie.Value = "Admin";
cookie.Expires = DateTime.Now.AddDays(-1);
Response.SetCookie(cookie);
}
And use the cookie as:-
if (Request.Cookies["Administrator"] != null)
{
if (Request.Cookies["Administrator"].Value == "Admin")
//some code
}
On log out I want this cookie should expire or gets deleted. So there I have written:- Seesion.Abandon();
Now even after I log-out, when I log back in to Home page..
the line Request.Cookies["Administrator"]
is stil not empty.
Strange...! Please let me know whats the reason and solution for this.
Upvotes: 12
Views: 61441
Reputation: 29000
You can try with
Session.Abandon();
Response.Cookies.Clear();
Or also
YourCookies.Expires = DateTime.Now.AddDays(-1d);
Link : http://msdn.microsoft.com/en-us/library/ms178195%28v=vs.100%29.aspx
Upvotes: 9
Reputation: 1821
Seems to me that your line
cookie.Expires = DateTime.Now.AddDays(-1);
should be immediately expiring your cookie as it is.
If you just typed it wrong then good news! you can expire your cookie by setting the expiry date in the past.
Upvotes: 4
Reputation: 16310
From MSDN DOCUMENTATION,
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.
You can do like this:
if (Request.Cookies["Administrator"] != null)
{
HttpCookie myCookie = new HttpCookie("Administrator");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
Upvotes: 17
Reputation: 4817
You have to assign an expiration date in the past to remove a specific cookie:
HttpCookie myCookie = new HttpCookie("Administrator");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
More info can be found at this msdn article:
Upvotes: 9