2017-03-02 7 views
0

ユーザー名を使用する代わりに、ApplicationUserクラスに存在するDisplayName列の値を表示します。ASP.NET MVC表示ユーザーフルネーム

ここでsolutionに基づいて、カスタムクラスを作成し、Global.asax Application Startで初期化しました。

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拡張メソッド作成します。私はそれをテストしていませんが、それはであなたを指している必要があり

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

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; 
    } 
} 

そして、あなたはこのようにそれを使用することができるはずですが正しい方向。

関連する問題