【问题标题】:How to display Name instead of UserName with User.Identity.Name in MVC如何在 MVC 中使用 User.Identity.Name 显示名称而不是用户名
【发布时间】:2015-10-23 09:45:50
【问题描述】:

关于这个问题有很多话题,没有找到适合我的愿望。

在 MVC5 中,_LoginPartial 中有这个函数User.Identity.GetUserName(),它显示了实际用户的用户名。

我想显示来自 ApplicationUser 的名称,其中包含属性:

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

我可以使用静态函数来获取名称,例如:

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

我不想再次查询数据库,我想使用这个User.Identity.Name,但是这个函数正在返回用户名,我需要以某种方式覆盖。

如何使用 User.Identity.Name 获取名称?

【问题讨论】:

标签: c# asp.net-mvc entity-framework asp.net-identity


【解决方案1】:
User.FindFirst("name").Value

即搜索声明以获取显示字符串。 "name" = 获取的身份的显示名称。

【讨论】:

  • 嗨@Dkumar,如果您在代码前面放置四个空格,它将被格式化为有助于澄清答案不同部分的代码。
【解决方案2】:

在我的脑海中,UserManager 有一个从 UserId 获取 ApplicationUser 的方法。然后使用 ApplicationUser 对象,您可以获得 Name 属性。类似的东西:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-17
    • 1970-01-01
    • 2021-10-31
    • 2020-10-12
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    相关资源
    最近更新 更多