解决方法
因为用户不能以正常方式在Identity中播种,就像其他表使用.NET Core 2.1的.HasData()播种一样.
.NET Core 2.1中的种子角色使用ApplicationDbContext类中给出的代码:
protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); // Customize the ASP.NET Identity model and override the defaults if needed. // For example,you can rename the ASP.NET Identity table names and more. // Add your customizations after calling base.OnModelCreating(builder); modelBuilder.Entity<IdentityRole>().HasData(new IdentityRole { Name = "Admin",normalizedname = "Admin".toupper() }); }
具有角色的种子用户按照以下步骤操作.
第1步:创建新类
public static class ApplicationDbInitializer { public static void SeedUsers(UserManager<IdentityUser> userManager) { if (userManager.FindByEmailAsync("abc@xyz.com").Result==null) { IdentityUser user = new IdentityUser { UserName = "abc@xyz.com",Email = "abc@xyz.com" }; IdentityResult result = userManager.CreateAsync(user,"PasswordHere").Result; if (result.Succeeded) { userManager.AddToRoleAsync(user,"Admin").Wait(); } } } }
步骤2:现在修改Startup.cs类中的ConfigureServices方法.
修改前:
services.AddDefaultIdentity<IdentityUser>() .AddEntityFrameworkStores<ApplicationDbContext>();
修改后:
services.AddDefaultIdentity<IdentityUser>().AddRoles<IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>();
步骤3:修改Startup.cs类中Configure Method的参数.
修改前:
public void Configure(IApplicationBuilder app,IHostingEnvironment env) { //.......... }
修改后:
public void Configure(IApplicationBuilder app,IHostingEnvironment env,UserManager<IdentityUser> userManager) { //.......... }
第4步:调用Seed(ApplicationDbInitializer)类的方法:
ApplicationDbInitializer.SeedUsers(userManager);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。