How to delete a cookie on a specific page?

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

+4
source share
4 answers

Microsoft: how to delete a cookie

You cannot directly delete the cookie on the user's computer. However, you can direct the user's browser to delete cookies by setting the cookie expiration date to a past date. The next time the user makes a request for a page in the domain or path that sets the cookie, the browser determines that the cookie has expired and deleted it.

To set a cookie expiration date

  • Determine if a cookie exists in the request, and if so, create a new cookie with the same name.
  • Set the cookie expiration date to the past.
  • Add a cookie to the Cookies Response collection object.

The following code example shows how to set an expiration date in 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 from the Cookies collection removes the cookie from the collection on the server side, so the cookie will not be sent to the client. However, this method does not remove the cookie from the client if it already exists.

+7
source

Did you try to end your cookie?

 protected void btnDelete_Click(object sender, EventArgs e) { Response.Cookies["cookie_name"].Expires = DateTime.Now.AddDays(-1); } 
+3
source

How to delete a cookie

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

You must first set the cookie expiration date to the previous date.

Example:

  HttpCookie newCookie = new HttpCookie("newCookie"); newCookie.Expires = DateTime.Now.AddDays(-1); Response.Cookies.Add(newCookie); 

Now just doing this will not help, since the cookie will not be physically deleted. You need to delete the cookie.

  if (newCookie.Expires < DateTime.Now) { Request.Cookies.Remove("newCookie"); } 

Here you go. This applies to any page within the solution.

0
source

Source: https://habr.com/ru/post/1301530/


All Articles