Request.Cookies 中的双重 cookie

aik*_*ixd 1 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

它工作正常,但是当我检查 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());
}
Run Code Online (Sandbox Code Playgroud)

Lob*_*ity 5

代替:

Response.Cookies.Add(cookie);
Run Code Online (Sandbox Code Playgroud)

用:

Response.Cookies.Set(cookie);
Run Code Online (Sandbox Code Playgroud)

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