Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove cookie on log-out

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.

like image 657
Kings Avatar asked Oct 10 '12 18:10

Kings


2 Answers

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

like image 168
Aghilas Yakoub Avatar answered Oct 17 '22 09:10

Aghilas Yakoub


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);
}
like image 17
Akash KC Avatar answered Oct 17 '22 08:10

Akash KC