我正在尝试使用ASP.NET MVC实现“记住我”功能。它使用如下定义的自定义身份验证过程。
的Web.config:
<authentication mode="Forms">
<forms loginUrl="/Account/Login" defaultUrl="/Home/MyAccount" timeout="43200"/>
</authentication>
持久cookie的代码:
public void SignIn(string userName, bool createPersistentCookie) {
int timeout = createPersistentCookie ? 525600 : 120; // Timeout in minutes, 525600 = 365 days.
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(userName, createPersistentCookie, timeout);
string encrypted = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
cookie.Expires = System.DateTime.Now.AddMinutes(timeout);
HttpContext.Current.Response.Cookies.Add(cookie);
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
}
检索cookie的代码:
if (System.Web.HttpContext.Current.Request.Cookies.AllKeys.Contains(FormsAuthentication.FormsCookieName)) {
cookie = System.Web.HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
}
当前代码检查Session以进行身份验证。我想添加从cookie获取userName的功能。我有两个问题:
干杯,
迪安
答案 0 :(得分:6)
获取cookie:
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(FormsAuthentication.FormsCookieName);
解决它:
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
var userName = ticket.UserData