使用SimpleMembership获取用户信息

4

仍在尝试掌握使用MVC4的新SimpleMembership。我更改了模型以包括名字和姓氏,这很好地起作用。

我想要更改登录时显示的信息,所以不想在视图中使用User.Identity.Name,而是想要像User.Identity.Forename这样做,有什么最好的方法来实现这一点呢?

1个回答

5
你可以利用 ASP.NET MVC 中可用的 @Html.RenderAction() 特性来显示此类信息。 _Layout.cshtml 视图
@{Html.RenderAction("UserInfo", "Account");}

视图模型

public class UserInfo
{
    public bool IsAuthenticated {get;set;}
    public string ForeName {get;set;}
}

账户控制器

public PartialViewResult UserInfo()
{
   var model = new UserInfo();

   model.IsAutenticated = httpContext.User.Identity.IsAuthenticated;

   if(model.IsAuthenticated)
   {
       // Hit the database and retrieve the Forename
       model.ForeName = Database.Users.Single(u => u.UserName == httpContext.User.Identity.UserName).ForeName;

       //Return populated ViewModel
       return this.PartialView(model);
   }

   //return the model with IsAuthenticated only
   return this.PartialView(model);
}

用户信息视图

@model UserInfo

@if(Model.IsAuthenticated)
{
    <text>Hello, <strong>@Model.ForeName</strong>!
    [ @Html.ActionLink("Log Off", "LogOff", "Account") ]
    </text>
}
else
{
    @:[ @Html.ActionLink("Log On", "LogOn", "Account") ]
}

这样做有几个好处,并且引入了一些选项:

  1. 使您的视图无需在HttpContext中嗅探。让控制器处理它。
  2. 现在您可以将其与 [OutputCache] 属性组合使用,因此您不必在每个页面中渲染它。
  3. 如果需要向UserInfo屏幕添加更多内容,只需更新ViewModel并填充数据即可。没有魔法,没有ViewBag等。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接