您可以利用身份验证 cookie 中的 userdata 字段存储身份验证会话期间的数据。
以下代码是默认 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) 更改为您希望身份验证会话保持有效的任何内容。