“删除”cookie无效

时间:2013-01-02 20:44:56

标签: c# asp.net cookies

所以我的一位同事使用以下代码从浏览器中“删除”了cookie。这应该有效,但在加载页面后立即检查cookie仍然存在cookie。这段代码有问题还是有更大的问题?

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

2 个答案:

答案 0 :(得分:1)

这是我用来杀死cookie的代码,它适用于我。

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

确保将cookie写入您正在执行的响应中。

答案 1 :(得分:0)

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

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