我正在尝试使用Cookie在登录页面中为用户名实现“记住我”。
我试图通过在cookie对象上使用Values.Add来实现这一点:
ck.Values.Add("username", txtUName.Value);
但是,当我以这种方式添加值时,身份验证会中断。 (如果我删除线路认证再次工作。)
如何保存用户名中存储的用户名而不会破坏它?
此位的完整代码是:
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);
答案 0 :(得分:2)
我设法直接从FormsAuthenticationTicket获得了我需要的东西:
if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value);
txtUName.Value = ticket.Name;
}
答案 1 :(得分:1)
尝试使用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);
}