1

我正在尝试使用 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);
4

2 回答 2

2

I managed to get what I needed direct from the FormsAuthenticationTicket:

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


               txtUName.Value = ticket.Name;
            }
于 2013-10-29T12:18:24.567 回答
1

尝试从此处使用此示例并阅读他们所写的内容。我在我的测试项目中测试它并且它有效。

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);
}
于 2013-10-29T12:25:28.020 回答