我需要在我的 Web 应用程序第一次启动时创建用户和角色。为此,我将代码写入Configure()
.Startup.cs
当我运行我的应用程序时,我收到此错误:
mscorlib.dll 中发生了“System.AggregateException”类型的异常,但在调用我的第一个函数“CreateUsers”时未在用户代码中处理
代码:
public async void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider, ApplicationDbContext context)
{
...
await CreateUsers(context, serviceProvider);
await CreateRoles(context, serviceProvider);
}
private async Task CreateUsers(ApplicationDbContext context, IServiceProvider serviceProvider)
{
List<ApplicationUser> users = new List<ApplicationUser>();
users.Add(new ApplicationUser { UserName = "devUser", Email = "dev@dev.com", LastName = "dev", FirstName = "dev", PasswordHash = "devpassword" });
users.Add(new ApplicationUser { UserName = "workUser", Email = "work@work.com", LastName = "work", FirstName = "work", PasswordHash = "workPassword" });
foreach(var user in users)
{
var userExist = await _userManager.FindByEmailAsync(user.Email);
if(userExist != null)
{
await _userManager.CreateAsync(user, user.PasswordHash);
context.Users.Add(user);
context.SaveChanges();
}
}
}
private async Task CreateRoles(ApplicationDbContext context, IServiceProvider serviceProvider)
{
var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
List<IdentityRole> roles = new List<IdentityRole>();
roles.Add(new IdentityRole { Name = "Developer", NormalizedName = "DEVELOPER" });
roles.Add(new IdentityRole { Name = "Work", NormalizedName = "WORK" });
roles.Add(new IdentityRole { Name = "Admin", NormalizedName = "ADMIN" });
roles.Add(new IdentityRole { Name = "Redacteur", NormalizedName = "REDACTEUR" });
roles.Add(new IdentityRole { Name = "Correcteur", NormalizedName = "CORRECTEUR" });
roles.Add(new IdentityRole { Name = "Membre", NormalizedName = "MEMBRE" });
foreach(var role in roles)
{
var roleExist = await RoleManager.RoleExistsAsync(role.Name);
if(!roleExist)
{
context.Roles.Add(role);
context.SaveChanges();
}
}
var devuser = await UserManager.FindByEmailAsync("dev@dev.com");
await UserManager.AddToRoleAsync(devuser, "DEVELOPER");
var work = await UserManager.FindByEmailAsync("work@work.com");
await UserManager.AddToRoleAsync(work, "WORK");
}