2017-03-02 75 views
0

而不是使用用戶名,我想顯示來自我的ApplicationUser類中存在的DisplayName列的值。ASP.NET MVC顯示用戶全名

基於這裏的solution,我創建了一個自定義類,並在Global.asax中應用程序啓動初始化。

public class UserProfileActionFilter: ActionFilterAttribute 
{ 
    public override void OnResultExecuting(ResultExecutingContext filterContext) 
    { 
     ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId()); 
     if (user != null) 
     { 
      filterContext.Controller.ViewBag.DisplayName = user.DisplayName; 
     } 

    } 

} 

然後,我在LogOnPartialView中引用以下ViewBag.DisplayName。

但該類被通過了申請擊中多次登錄,操作執行過程中和等。我很擔心這是否會導致開銷到數據庫。

回答

1

我將創建一個IIdentity擴展方法:

public static class IIdentityExtensions 
{ 
    public static string GetUserDisplayName(this IIdentity identity) 
    { 
     ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId()); 
     if (user != null) 
     { 
      return user.DisplayName; 
     } 
     return string.Empty; 
    } 
} 

然後你應該能夠使用它像這樣:

<p>User Name: @User.Identity.GetUserDisplayName()</p> 

我沒有測試它,但它應該指向你正確的方向。