我想知道当用户点击“记住我”复选框时,如何通过Cookie设置@User.Identity.Name
。
Cookie代码
if (_model.RememberMe)
{
HttpCookie cookie = new HttpCookie("login");
cookie.Values.Add("username", _model.Username);
cookie.Expires = DateTime.Now.AddDays(30);
Response.Cookies.Add(cookie);
}
首次登录代码
if (Membership.ValidateUser(Username,Password))
{
RememberMe();
FormsAuthentication.RedirectFromLoginPage(Username, false);
}
首次登录时设置了Identity.name,但是当我关闭浏览器并返回该站点时。它在没有用户输入凭据的情况下正确登录,但Identity.name
为空。
if (Request.Cookies["login"] != null)
{
// We know the automatic log in has worked as it comes into here...
}
用户通过登录页面后我需要做什么才能设置iPrincipal
对象?
由于
答案 0 :(得分:1)
请尝试以下代码 注意:请在页面视图上查看,而不是在创建cokies时使用相同的方法
private void CreateCokies(string userName)
{
var authTicket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddMinutes(30), true, userName);
string cookieContents = FormsAuthentication.Encrypt(authTicket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieContents)
{
Expires = authTicket.Expiration,
Path = FormsAuthentication.FormsCookiePath
};
Response.Cookies.Add(cookie);
}