User.Identity.Name 或 GetUserName 不适用于 MVC 5

User.Identity.Name or GetUserName not working on MVC 5

我在 MVC 系统上工作,我已经实现了将日志作为要显示的初始页面(如启动画面)放在视图中,一旦用户成功登录,将他们重定向到主视图。

接下来我需要做的是:

  1. 一个用户在主视图中,有一个部分我尝试显示用户名。例如:约翰·史密斯。为此,我使用了以下内容:

    User.Identity.Name 
    

    User.Identity.GetUserName
    

但其中 none 似乎有效。名称不显示。 查看我从 VS 创建 MVC 项目时生成的 tables,AspNetUser table 没有任何名称、姓氏或全名列。相反,它有一些列,其中之一是 UserName,它存储这样的数据:john.smith.

那么,为了显示用户的名字和姓氏,我应该在那个 table 上创建额外的列并更新注册视图以输入这些数据吗?

提前致谢

首先,如果您已正确设置 ASP .NET Identity,或者如果您使用的是 ASP .NET Identity 附带的项目启动模板,那么以下内容应该可以在视图中使用:

@User.Identity.Name

@User.Identity.GetUserName()

此外,如果您想向用户添加自定义属性,则必须将这些属性添加到 ApplicationUser class 或 IdentityUser 继承的任何其他 class然后在 IdentityDbContext...

中使用 class
public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection")
    {
    }
}

Check this