【问题标题】:Usermanager with model inherited from applicationUser具有从 applicationUser 继承的模型的用户管理器
【发布时间】:2017-03-31 10:22:34
【问题描述】:

我是 ASP.NET 的早期初学者,我正在尝试在 ASP.NET-MVC 项目中使用 Identity 框架构建用户系统。

我想让“Admin”用户实体从我的模型中默认创建的基本实体“applicationUser”继承(我的小改动):

public class ApplicationUser : IdentityUser
{
    [Required]
    [StringLength(50)]
    [Display(Name = "Last Name")]
    public string LastName { get; set; }
    [Required]
    [StringLength(50, ErrorMessage = "First name cannot be longer than 50 characters.")]
    [Column("FirstName")]
    [Display(Name = "First Name")]
    public string FirstMidName { get; set; }

    [Display(Name = "Full Name")]
    public string FullName
    {
        get
        {
            return LastName + ", " + FirstMidName;
        }
    }
}
public class Admin: ApplicationUser
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int AdID;
}

我还将添加来自 applicationUser 的 2 个其他继承,我希望为不同的用户提供单独的模型,以将不同的信息存储在他们的数据库文件中,并让他们所有人都登录到我的网站。

在启动时,我尝试使用此代码最初添加管理员用户(在 stackoverflow 答案中的某处获取):

        public static async Task CreateRoles(SchoolContext context, IServiceProvider serviceProvider)
        {

            var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
            var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
            // First, Creating User role as each role in User Manager  
            List<IdentityRole> roles = new List<IdentityRole>();

            roles.Add(new IdentityRole { Name = "Student", NormalizedName = "STUDENT" });
            roles.Add(new IdentityRole { Name = "ADMIN", NormalizedName = "ADMINISTRATOR" });
            roles.Add(new IdentityRole { Name = "Professor", NormalizedName = "PROFESSOR" });

            //Then, the machine added Default User as the Admin user role
            foreach (var role in roles)
            {
                var roleExit = await roleManager.RoleExistsAsync(role.Name);
                if (!roleExit)
                {
                    context.Roles.Add(role);
                    context.SaveChanges();
                }
            }

            await CreateUser(context, userManager);
        }


        private static async Task CreateUser(SchoolContext context, UserManager<ApplicationUser> userManager)
        {
            var adminUser = await userManager.FindByEmailAsync("alpha@lms.com");
            if (adminUser != null)
            {
                if (!(await userManager.IsInRoleAsync(adminUser, "ADMINISTRATOR")))
                    await userManager.AddToRoleAsync(adminUser, "ADMINISTRATOR");
            }
            else
            {
                var newAdmin = new applicationUser()
                {
                    UserName = "alpha@lms.com",
                    Email = "alpha@lms.com",
                    LastName = "Admin",
                    FirstMidName = "Admin",

                };
                var result = await userManager.CreateAsync(newAdmin, "password123;");
                if (!result.Succeeded)
                {
                    var exceptionText = result.Errors.Aggregate("User Creation Failed
                     - Identity Exception. Errors were: \n\r\n\r", 
                    (current, error) => current + (" - " + error + "\n\r"));
                    throw new Exception(exceptionText);
                }
                await userManager.AddToRoleAsync(newAdmin, "ADMINISTRATOR");
            }
        }

但是当我尝试这样做时,我收到了一个异常: “无法将值 NULL 插入到列‘鉴别器’、表‘aspnet-University;列不允许空值。插入失败。 声明已终止。”

如果我尝试在“new Admin”而不是“new applicationUser”上更改变量 Admin 类型,我会收到另一个异常: 找不到实体类型“管理员”。确保实体类型已添加到模型中。

我知道这个问题是关于身份框架的基础知识;我还不太了解它们;我刚刚开始了解它的原理,但我不知道如何处理我的问题。

我猜我需要创建 New UserManager,它将能够操作从基本 applicationUser 模型继承的实例。如果您向我推荐有关此主题的相关资源并帮助我解决问题,我将很高兴。

【问题讨论】:

    标签: entity-framework asp.net-identity asp.net-core-mvc asp.net-core-identity


    【解决方案1】:

    如果有人有这个问题 - 我决定不使用从 ApplicationUser 继承,因为这显然是错误的方法,而是从 IdentityUser 类继承所有自定义用户模型。为了完成这项工作,我在 StartUp Configure 服务中添加了以下几行:

    services.AddIdentity <IdentityUser, IdentityRole>()
                    .AddEntityFrameworkStores<YourContext>()
                    .AddDefaultTokenProviders();
    

    我的用户模型声明如下:

    public class Admin : IdentityUser
        { 
        }
    

    在上下文文件中我有这个:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                modelBuilder.Entity<IdentityUser>(i => {
                    i.ToTable("Users");
                    i.HasKey(x => x.Id);
                });
                modelBuilder.Entity<IdentityRole<>(i => {
                    i.ToTable("Role");
                    i.HasKey(x => x.Id);
                });
    }
    

    有了这段代码,我可以使用 Identity 的 UserManager 和 RoleManager 而无需额外的更改。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多