如何通过页面设置保留名称,姓氏等信息的全局用户数据?如果我使用会话变量,它会在auth cookie之前到期
谢谢!
您可以使用auth cookie中的userdata字段存储auth会话时间的数据.
下面的代码是默认MVC项目中AccountController的LogOn操作:
[HttpPost] public ActionResult LogOn(LogOnModel model, string returnUrl) { if (ModelState.IsValid) { if (Membership.ValidateUser(model.UserName, model.Password)) { FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe); if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) { return Redirect(returnUrl); } else { return RedirectToAction("Index", "Home"); } } else { ModelState.AddModelError("", "The user name or password provided is incorrect."); } } // If we got this far, something failed, redisplay form return View(model); }
你可以替换:
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
有:
string fullName = "User full name"; FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2, model.Email, DateTime.Now, DateTime.Now.AddDays(2), model.RememberMe, fullName); string encTicket = FormsAuthentication.Encrypt(ticket); Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket) { Expires = DateTime.Now.AddDays(2) });
如果您想存储的数据超过普通字符串的数据,则必须查看某种数据序列化程序.
然后,在使用auth cookie时,您必须实现一些解析序列化数据的东西.
数据可通过:
((FormsIdentity)User.Identity).Ticket.UserData;
希望有所帮助
编辑: 同时将DateTime.Now.AddDays(2)更改为您希望auth会话保持有效的任何内容.