[SOLVED] Asp.Net – How to expire Cookie

Issue

Tried

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

and also tried by commenting uncommented code and uncommenting commented code but

 string a = Request.Cookies["IsGuest"].Value;

Always running and Request.Cookies["IsGuest"] is never null

Solution

You got the right concept for deleting a cookie programmatically:

HttpCookie myCookie = new HttpCookie("IsGuest"); 
cookie.Expires = DateTime.Now.AddDays(-1d); 
Response.Cookies.Add(cookie);

However, you missed one point. The above change won't be effective until the postback completes and subsequently user initiates a new request.

MSDN says:

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.

So, the below code illustrates more here::

protected void DeleteCookie_ButtonClick(object sender, EventArgs e)
    {
        if (Request.Cookies["IsGuest"] != null)
        {
            HttpCookie myCookie = new HttpCookie("IsGuest"); 
            myCookie.Expires = DateTime.Now.AddDays(-1d); 
            Response.Cookies.Add(myCookie);
        }
        
        // this will always be true here as the Request  i.e HttpRequest isn't 
        // modified actually as the postback isn't complete and we are accessing 
        // the Cookies collection of same request (not a new request)
        if (Request.Cookies["IsGuest"] != null)
        {
            Label1.Text = "Cookie Collection  can't be modified without 
                           making a new request";
        }

    }
    
   // suppose after postback completes, 
   // user clicks a buttonn to check the cookie, 
   // which in turn is a new request/postback/....
    protected void CheckCookie_ButtonClick(object sender, EventArgs e)
    {
        if (Request.Cookies["IsGuest"] != null)
        {
            Label1.Text = "Cookie is present!";                
        }
        else
        {
            Label1.Text = "No Cookie is present!";                
        }
    }

One last Note::

Calling the Remove method of the Cookies collection removes the cookie on the server side, so the cookie will not be sent to the client. However, the method does not remove the cookie from the client if it already exists there.

Answered By – R.C

Answer Checked By – Candace Johnson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *