Request.Cookies中的双cookie

时间:2010-12-24 01:59:32

标签: asp.net authentication cookies

我在global.asax中有以下代码:

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
    if (Request.Cookies["AUTH"] != null)
    {
        FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Request.Cookies["AUTH"].Value);

        HttpContext.Current.User = new MyPrincipal(ticket.Name);

        HttpCookie cookie = Request.Cookies["AUTH"];
        cookie.Expires = DateTime.Now.AddDays(30);

        Response.Cookies.Add(cookie);
    }
}

它工作正常,但是当我检查了Request.Cookies集合时,AUTH cookie有2个条目,具有不同的值。怎么样?

这是登录页面中的身份验证过程代码:

if (Account.Authenticate(login.Text, pass.Text))
{
    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(login.Text, true, 43200);

    HttpCookie cookie = new HttpCookie("AUTH");
    cookie.Expires = DateTime.Now.AddDays(30);
    cookie.HttpOnly = true;
    cookie.Value = FormsAuthentication.Encrypt(ticket);

    Response.Cookies.Add(cookie);


    Response.Redirect(Page.Request.UrlReferrer.ToString());
}

2 个答案:

答案 0 :(得分:4)

而不是:

Response.Cookies.Add(cookie);

使用:

Response.Cookies.Set(cookie);

Add允许重复。 Set没有,因此可用于更新现有Cookie。

答案 1 :(得分:2)

查看您的Application_AuthenticateRequest例程,您似乎使用'HttpCookie cookie = Request.Cookies [“AUTH”];'访问现有cookie,但随后使用'Response添加另一个cookie。 Cookies.Add(饼干);'

您可以删除最后一行,因为当您已在集合中存在另一个Cookie时,您不需要添加另一个Cookie。或者在Add之前添加一个Remove,以便在再次添加之前从集合中删除现有的命名cookie。

相关问题