简体   繁体   中英

How to display Name instead of UserName with User.Identity.Name in MVC

There are many topics on this issue, did not found one to fit my wish.

In MVC5, in _LoginPartial , there is this function User.Identity.GetUserName() , which is displaying the UserName of the actual user.

I want to display the Name, from ApplicationUser, which contain the properties:

public ApplicationUser()
{
   Name = FirstName + " " + LastName;
}
public FirstName {get;set;}
public LastName {get;set;}
public Name {get;}

I have the posibility to use a static function to get the Name, like:

function.Name(User.Identity.GetUserId()) .

I do not want to query again the database, I want to use this User.Identity.Name , but this function is returning the UserName, I need to override somehow.

How can I get the Name, using User.Identity.Name ?

User.FindFirst("name").Value

ie search through claims to get the display string. "name" = display name for the identity fetched.

Off the top of my head UserManager has a method to get ApplicationUser from UserId. Then with the ApplicationUser object you can get the Name property. Something like:

ApplicationUser user = UserManager.GetUserById(User.Identity.GetUserId());
user.Name;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM