如何在MVC中使用User.Identity.Name显示姓名而不是用户名
如何在MVC中使用User.Identity.Name显示姓名而不是用户名
在这个问题上有很多话题,但没有找到符合我愿望的一个。
在MVC5中,在_LoginPartial中,有这个函数User.Identity.GetUserName(),它显示实际用户的用户名。
我想显示ApplicationUser中的Name,其中包含以下属性:
public ApplicationUser()
{
Name = FirstName + " " + LastName;
}
public FirstName {get;set;}
public LastName {get;set;}
public Name {get;}
我有可能使用一个静态函数来获取Name,例如:function.Name(User.Identity.GetUserId())。
我不想再次查询数据库,我想使用User.Identity.Name,但是这个函数返回的是用户名,我需要以某种方式进行覆盖。
如何使用User.Identity.Name获取Name?
在MVC中,我们通常使用User.Identity.Name
来获取当前登录用户的用户名。然而,有时我们希望显示用户的真实姓名而不是用户名。那么,我们如何使用User.Identity.Name
来显示姓名呢?
首先,我们需要使用UserManager类的方法来根据用户ID获取ApplicationUser对象。然后,我们可以通过该对象的Name属性来获取用户的姓名。具体代码如下:
ApplicationUser user = UserManager.GetUserById(User.Identity.GetUserId()); user.Name;
通过以上代码,我们可以得到当前登录用户的真实姓名。