我正在尝试实现一个“记住我”的用户名在登录页面使用cookies。
我试图通过在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);发布于 2013-10-29 20:18:25
我设法直接从FormsAuthenticationTicket获得了我需要的东西:
if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value);
txtUName.Value = ticket.Name;
}发布于 2013-10-29 20:25:28
尝试使用here中的这个示例,并阅读他们所写的内容。我在我的测试项目中对它进行了测试,它可以正常工作。
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);
}https://stackoverflow.com/questions/19657622
复制相似问题