Search code examples
c#asp.net-mvcasp.net-identity

ASP.NET MVC Display User Full Name


Instead of using user name, I want to display the value from column DisplayName which exists in my ApplicationUser class.

Based on the solution here, I created a custom class and initialize it in 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;
        }

    }

}

I then refer following ViewBag.DisplayName in the LogOnPartialView.

But this class is being hit multiple times through out the application, during login, action execution and etc. I'm worried if this will cause overhead to the database.


Solution

  • I would create an IIdentity extension method:

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

    And then you should be able to use it like this:

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

    I haven't tested it but it should point you in the right direction.