开发者

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?


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.


Have you tried expiring your cookie?

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


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);
}


First you have to set the expiry date of the cookie to a previous date.

For Example :

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

Now only doing this will not be helpful as the cookie will not be physically removed. You have to remove the cookie.

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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜