2

So one of my co-workers used the following code to "remove" the cookies from the browser. This should work, but checking the cookies right after loading the page the cookies are still there. Is there something wrong with this code or is there a bigger problem?

protected void Page_Load(object sender, EventArgs e)
{
    HttpCookie aCookie;
    string cookieName;
    int limit = Request.Cookies.Count;

    for (int i = 0; i < limit; i++)
    {
        cookieName = Request.Cookies[i].Name;
        aCookie = new HttpCookie(cookieName);
        aCookie.Expires = DateTime.Now.AddDays(-1);

        if (cookieName != "Lang")
            Response.Cookies.Add(aCookie);
    }
    FormsAuthentication.SignOut();
    Response.Redirect("/default.aspx");
}
4

2 回答 2

1

This is the code that I've used to kill the cookie and it works for me.

string cookieName;
    int limit = Request.Cookies.Count;


    for (int i = 0; i < limit; i++)
    {
        cookieName = Request.Cookies[i].Name;
        var cookie = new HttpCookie(cookieName);
        cookie.Value = "";
        cookie.Expires = DateTime.Now.AddDays(-3);
        //Only if HTTPS
        cookie.Secure = true;
        //Only if a domain is specified, and obviously, it should match the domain of the app
        cookie.Domain = "XYZ";

        Response.Cookies.Add(cookie);
    }
    FormsAuthentication.SignOut();
    Response.Redirect("/default.aspx");

Make sure you write the cookie to the response, which you are doing.

于 2013-01-02T20:48:32.453 回答
0

您的语法看起来是正确的,但是,我认为您缺少的是将 cookie 的更改发布回系统。

您设置了 cookie 过期时间,但您需要Response.Cookies.Add()使用相同的名称来覆盖旧的 cookie。

于 2013-01-02T20:49:20.693 回答