UserManager在不抛出任何Exception的情况下退出该函数



我正试图让我的MVC应用程序在数据库中创建初始预览用户,代码如下:

private async Task CreateStartupUsers(UserManager<IdentityUser> userManager)
{
List<IdentityUser> admins = new List<IdentityUser>
{
new IdentityUser
{
UserName = "admin@admin.com",
Email = "admin@admin.com",
EmailConfirmed = true
}
};
...
foreach (var admin in admins)
{
if (await userManager.FindByNameAsync(admin.UserName) != null)
{
continue;
}
await userManager.CreateAsync(admin, DefaultPassword);
IdentityUser user = await userManager.FindByNameAsync(admin.UserName);
await userManager.AddToRoleAsync(user, "Admin");
}

老实说,除了在非异步public IConfiguration Configuration { get; }中调用此函数之外,我在这里没有看到任何问题,但我认为这并不能解释在调试期间调用userManager的指令没有执行并退出函数的事实。

我还制作了一个非常类似的功能来创建初始用户角色,它非常完美。

private async Task CreateRoles(RoleManager<IdentityRole> roleManager)
{
var roles = new List<IdentityRole>
{
new IdentityRole
{
Name = "Admin"
},
new IdentityRole
{
Name = "Employee"
},
new IdentityRole
{
Name = "Customer"
}
};
foreach (var role in roles)
{
if (await roleManager.RoleExistsAsync(role.Name)) continue;
var result = await roleManager.CreateAsync(role);
if (result.Succeeded) continue;
throw new Exception($"Could not create '{role.Name}' role.");
}
}

这些函数在Configure函数的StartUp.cs中被调用,如下所示:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, RoleManager<IdentityRole> roleManager, UserManager<IdentityUser> userManager)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseMigrationsEndPoint();
CreateRoles(roleManager);
CreateStartupUsers(userManager);
}

由于Configuration方法被称为同步的,并且它们的子方法是异步的,因此创建用户的方法在Configuration完成之前没有完成。由于Configuration必须为构建器返回void,我不得不进行以下更改:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, RoleManager<IdentityRole> roleManager, UserManager<IdentityUser> userManager)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseMigrationsEndPoint();
CreateRolesAndUsersAsync(roleManager, userManager).GetAwaiter().GetResult();
}

GetAwaiter()GetResult()添加到包含我想要执行的两个异步方法的方法中,我已经确保了它们的执行,并获得了预期的结果。

最新更新