首页 > 解决方案 > 为 AspNetUser 添加自定义字段

问题描述

我是 ASP.NET Core 的新手。如何在代码和 UI 中将自定义字段添加到我的用户模型?

当前的用户管理 UI 是这样的,但我想在模型、数据库和 UI 中添加一些额外的字段,例如信用或分数:

在此处输入图像描述

这是我的 AspNetUser 模型:

public partial class AspNetUsers
    {
        public AspNetUsers()
        {
            AspNetUserClaims = new HashSet<AspNetUserClaims>();
            AspNetUserLogins = new HashSet<AspNetUserLogins>();
            AspNetUserRoles = new HashSet<AspNetUserRoles>();
            AspNetUserTokens = new HashSet<AspNetUserTokens>();
        }

        public string Id { get; set; }
        public string UserName { get; set; }
        public string NormalizedUserName { get; set; }
        public string Email { get; set; }
        public string NormalizedEmail { get; set; }
        public bool EmailConfirmed { get; set; }
        public string PasswordHash { get; set; }
        public string SecurityStamp { get; set; }
        public string ConcurrencyStamp { get; set; }
        public string PhoneNumber { get; set; }
        public bool PhoneNumberConfirmed { get; set; }
        public bool TwoFactorEnabled { get; set; }
        public DateTimeOffset? LockoutEnd { get; set; }
        public bool LockoutEnabled { get; set; }
        public int AccessFailedCount { get; set; }

        public double Credit { get; set; }

        public virtual ICollection<AspNetUserClaims> AspNetUserClaims { get; set; }
        public virtual ICollection<AspNetUserLogins> AspNetUserLogins { get; set; }
        public virtual ICollection<AspNetUserRoles> AspNetUserRoles { get; set; }
        public virtual ICollection<AspNetUserTokens> AspNetUserTokens { get; set; }
    }

标签: asp.net-coreasp.net-mvc-scaffoldingef-core-2.2

解决方案


继承自 支持自定义用户数据IdentityUser。通常将这种类型命名为 ApplicationUser:

public class ApplicationUser : IdentityUser
{
    public string CustomTag { get; set; }
}

定制的详细步骤可以在定制模型文档中找到。

在 ASP.NET Core 2.1 或更高版本中,Identity 作为 Razor 类库提供。有关详细信息,请参阅ASP.NET Core 项目中的脚手架标识

搭建好脚手架后,可以在里面找到个人资料页面Areas.Identity.Pages.Account.Manage.Index.cshtml,可以在里面添加实体,InputModelIndex.cshtml.cs定义里面的数据OnGetAsyncOnPostAsync功能。


推荐阅读