Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I delete a cookie in a particular page?

I am creating a cookie in one page of an ASP.NET application and I want to delete it in another page. How do I do that?

like image 964
Surya sasidhar Avatar asked Dec 22 '22 05:12

Surya sasidhar


2 Answers

Microsoft: How To Delete a Cookie

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.

To assign a past expiration date on a cookie

  1. Determine whether the cookie exists in the request, and if so, create a new cookie with the same name.
  2. Set the cookie's expiration date to a time in the past.
  3. Add the cookie to the Cookies collection object of the Response.

The following code example shows how to set a past expiration date on a cookie.

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

Note: Calling the Remove method of the Cookies collection removes the cookie from the collection 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.

like image 157
Noah Heldman Avatar answered Feb 08 '23 22:02

Noah Heldman


Have you tried expiring your cookie?

protected void btnDelete_Click(object sender, EventArgs e)
{
    Response.Cookies["cookie_name"].Expires = DateTime.Now.AddDays(-1);
}
like image 36
Chase Florell Avatar answered Feb 08 '23 22:02

Chase Florell