我是MVC的新手,所以这个问题可能并不重要。在我的LogOn操作中,我执行以下操作:
public ActionResult LogOn(UserModel userModel, string returnUrl)
{
ActionResult retvalue = null;
UserProfile user = MyDatabaseAccess.Instance.GetAuthenticatedUser(userModel.EmailAddress, userModel.Password);
if (user != null)
{
FormsAuthentication.SetAuthCookie(userModel.EmailAddress, userModel.RememberMe);
Session["LoggedOnUser"] = user;
if (Url.IsLocalUrl(returnUrl))
{
retvalue = Redirect(returnUrl);
}
else
{
retvalue = RedirectToAction("Home", "Home");
}
}
else
{
retvalue = RedirectToAction("LogOn", "Account");
}
return retvalue;
}在这一点上,我的会话有完整的UserProfile对象,我通过网站使用它,到目前为止一切都正常。
下一次用户访问网站时,该用户已经通过了身份验证(rememberme设置为true),并且User.Identity.Name具有之前通过身份验证的用户的电子邮件地址,这是正确的。问题是,我想像在LogOn操作中一样将UserProfile加载到会话中。我想要一个单独的地方,而不是在每个授权的操作中。
有这样的办法吗?
发布于 2012-10-24 04:22:32
一种方法是创建一个SecurityContext,您可以通过它访问用户信息。然后,您可以将SecurityContext保留在会话中。如果用户已通过身份验证,但会话中不存在SecurityContext,则从Db读取数据并将其再次添加到会话中。
可能是这样的:
public static class SecurityContext
{
public static UserProfile CurrentUser
{
get
{
var user = HttpContext.Current.Session["CurrentUser"] as UserProfile;
if (user == null)
{
using (var ctx = new YourDbContext())
{
user = ctx.User.SingleOrDefault(u => u.UserName ==
HttpContext.Current.User.Identity.Name);
HttpContext.Current.Session["CurrentUser"] = user;
}
}
return user;
}
set
{
HttpContext.Current.Session["CurrentUser"] = value;
}
}
}在应用程序中的任何时候,您都可以通过调用SecurityContext.CurrentUser来访问您的用户配置文件
当然,您仍然需要在控制器/操作上使用[Authorized]属性来确保用户通过了身份验证。SecurityContext只是一个包装器,以便更容易地访问有关经过身份验证的用户的信息。
发布于 2012-10-24 04:32:34
一种更好的方法是实现自定义的IIdentity和/或IPrincipal。您可以将常用信息存储在身份验证cookie中。如果信息不敏感(例如,您只使用它来显示用户名,而不用于任何与安全相关的东西),那么您可以将其存储在您自己的cookie中。
这里有一篇好文章:
http://www.bradygaster.com/custom-authentication-with-mvc-3.0
https://stackoverflow.com/questions/13038541
复制相似问题