我有一个使用 Forms 身份验证和 SimpleMembershipProvider 的 MVC 4 项目设置。在我的用户表中,我还有一些其他属性,例如电子邮件、名字、姓氏等
如何在 Razor 视图中访问当前登录用户的个人资料?
我试过创建一个 BaseController,然后让其他控制器继承它,就像这样。
public class BaseController : Controller
{
public UserProfile CurrentUser;
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
if (this.HttpContext.User.Identity.IsAuthenticated)
{
var context = new UsersContext();
var user = context.UserProfiles.SingleOrDefault(u => u.UserName == WebSecurity.CurrentUserName);
CurrentUser = user;
}
}
}
然后在 HtmlExtension 方法中;
public static class HtmlExtensions
{
public static UserProfile CurrentUser(this HtmlHelper htmlHelper)
{
var controller = htmlHelper.ViewContext.Controller as BaseController;
if (controller == null)
{
throw new Exception("The controller used to render this view doesn't inherit from BaseController");
}
return controller.CurrentUser;
}
}
但是,如果我尝试检索用户的属性,这将不起作用,例如
@Html.CurrentUser.Firstname