2

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.