我有一个使用EF Core 2.1.0的ASP.NET Core 2.1.0应用程序.
I have an ASP.NET Core 2.1.0 application using EF Core 2.1.0.
我该如何向Admin用户播种数据库并赋予他/她一个Admin角色?我找不到与此有关的任何文档.
How do I go about seeding the database with Admin user and give him/her an Admin role? I cannot find any documentation on this.
推荐答案由于无法在Identity中以常规方式为用户添加种子,就像使用.NET Core 2.1的.HasData()为其他表添加种子一样.
As user cannot be seeded in a normal way in Identity just like other tables are seeded using .HasData() of .NET Core 2.1.
Microsoft建议:对于需要调用外部API的数据,例如ASP.NET Core Identity用户创建,建议使用自定义初始化逻辑.
Microsoft Recommendation: For data that requires calls to external API, such as ASP.NET Core Identity users creation it is recommended to use custom initialization logic.
种子角色:
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() }); }请按照以下步骤操作
使用角色来种子用户.
Seed Users With Roles by Following the steps given below.
步骤1:创建新课程
public static class ApplicationDbInitializer { public static void SeedUsers(UserManager<IdentityUser> userManager) { if (userManager.FindByEmailAsync("abc@xyz").Result==null) { IdentityUser user = new IdentityUser { UserName = "abc@xyz", Email = "abc@xyz" }; IdentityResult result = userManager.CreateAsync(user, "PasswordHere").Result; if (result.Succeeded) { userManager.AddToRoleAsync(user, "Admin").Wait(); } } } }步骤2:现在修改Startup.cs类中的ConfigureServices方法.
Step 2: Now Modify ConfigureServices method in Startup.cs class.
修改前:
services.AddDefaultIdentity<IdentityUser>() .AddEntityFrameworkStores<ApplicationDbContext>();修改后:
services.AddDefaultIdentity<IdentityUser>().AddRoles<IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>();步骤3:修改Startup.cs类中Configure方法的参数.
Step 3: Modify parameters of Configure Method in Startup.cs class.
修改前:
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { //.......... }修改后:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, UserManager<IdentityUser> userManager) { //.......... }第4步:我们的Seed(ApplicationDbInitializer)类的调用方法:
Step 4 : Calling method of our Seed (ApplicationDbInitializer) class:
ApplicationDbInitializer.SeedUsers(userManager);注意:您还可以像注入用户一样,将RoleManager和UserManager一起注入种子角色.
Note: You can also Seed Roles just like users by Injecting the RoleManager along with UserManager.
更多推荐
如何在EF Core 2.1.0中播种Admin用户?
发布评论