【问题标题】:Double cookie in Request.CookiesRequest.Cookies 中的双重 cookie
【发布时间】:2011-11-22 07:14:19
【问题描述】:

我在 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 集合时,有 2 个 AUTH cookie 条目,具有不同的值。怎么会?

这是登录页面中认证过程的代码:

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

【问题讨论】:

    标签: asp.net authentication cookies


    【解决方案1】:

    代替:

    Response.Cookies.Add(cookie);
    

    用途:

    Response.Cookies.Set(cookie);
    

    Add 允许重复。 Set 没有,所以它可以用来更新现有的 cookie。

    【讨论】:

      【解决方案2】:

      查看您的 Application_AuthenticateRequest 例程,您似乎正在使用 'HttpCookie cookie = Request.Cookies["AUTH"];' 访问现有 cookie,然后使用 'Response 添加另一个。 Cookies.Add(cookie);'.

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

      【讨论】:

      • 我想修改cookie的过期日期。据我了解,Response.Cookies 集合是空的,当我向其中添加 smth 时,应用程序只是添加了一个标题“set-cookie blah blah blah”......对吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-06
      • 2013-09-16
      • 2015-01-10
      • 1970-01-01
      • 1970-01-01
      • 2021-07-04
      相关资源
      最近更新 更多