如何将用户名值保存到 cookie,以便在用户想要被记住时可以检索它

本文关键字:用户 检索 保存 cookie | 更新日期: 2023-09-27 18:37:21

我正在尝试使用 cookie 为登录页面中的用户名实现"记住我"。

我正在尝试通过在cookie对象上使用Values.Add来执行此操作:

 ck.Values.Add("username", txtUName.Value);

但是,当我以这种方式添加值时,身份验证会中断。(如果我删除线路身份验证再次工作。

如何在不破坏 Cookie 的情况下保留存储在 Cookie 中的用户名?

此位的完整代码为:

            bool IsRemember = chkPersistCookie.Checked;
            FormsAuthenticationTicket tkt;
            string cookiestr;
            HttpCookie ck;
            tkt = new FormsAuthenticationTicket(1, txtUName.Value, DateTime.Now, DateTime.Now.AddMinutes(30), IsRemember, "your custom data");
            cookiestr = FormsAuthentication.Encrypt(tkt);
            ck = new HttpCookie("MYCOOKIEAPP", cookiestr);
            if (IsRemember)
            {
                ck.Expires = tkt.Expiration;
                ck.Values.Add("username", txtUName.Value);
            }
            else
            {
                ck.Values.Add("username", txtUName.Value);
                ck.Expires = DateTime.Now.AddMinutes(5);
            }
            ck.Path = FormsAuthentication.FormsCookiePath;
            Response.Cookies.Add(ck);

如何将用户名值保存到 cookie,以便在用户想要被记住时可以检索它

我设法直接从FormsAuthenticationTicket获得我需要的东西:

  if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
            {
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value); 

               txtUName.Value = ticket.Name;
            }

尝试从这里使用这个例子并阅读他们写的内容。我在我的测试项目中测试它并且它可以工作。

protected void Page_Load(object sender, EventArgs e)
{
    if(Request.Cookies["BackgroundColor"] != null)
    {
        ColorSelector.SelectedValue = Request.Cookies["BackgroundColor"].Value;
        BodyTag.Style["background-color"] = ColorSelector.SelectedValue;
    }
}
protected void ColorSelector_IndexChanged(object sender, EventArgs e)
{
    BodyTag.Style["background-color"] = ColorSelector.SelectedValue;
    HttpCookie cookie = new HttpCookie("BackgroundColor");
    cookie.Value = ColorSelector.SelectedValue;
    cookie.Expires = DateTime.Now.AddHours(1);
    Response.SetCookie(cookie);
}