【发布时间】:2020-04-05 16:58:06
【问题描述】:
我已关注this article,了解如何将角色播种到数据库。它通过在Program.cs 中创建的范围内调用播种方法来创建角色,如下所示:
public class Program
{
public static void Main(string[] args)
{
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
var serviceProvider = services.GetRequiredService<IServiceProvider>();
var configuration = services.GetRequiredService<IConfiguration>();
Seed.CreateRoles(serviceProvider, configuration).Wait();
}
catch (Exception exception)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(exception, "An error occurred while creating roles");
}
}
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
但是,在这一行:using (var scope = host.Services.CreateScope()),我在“主机”上得到一个红色波浪线:“名称'主机'在当前上下文中不存在”。如何让它在 Asp.Net Core 3.1 中工作?
这是播种方法:
public static class Seed
{
public static async Task CreateRoles(IServiceProvider serviceProvider, IConfiguration Configuration)
{
//adding customs roles
var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
string[] roleNames = { "Admin", "HRManager", "User" };
IdentityResult roleResult;
foreach (var roleName in roleNames)
{
// creating the roles and seeding them to the database
var roleExist = await RoleManager.RoleExistsAsync(roleName);
if (!roleExist)
{
roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
}
}
// creating a super user who could maintain the web app
var poweruser = new ApplicationUser
{
UserName = Configuration.GetSection("AppSettings")["UserEmail"],
Email = Configuration.GetSection("AppSettings")["UserEmail"]
};
string userPassword = Configuration.GetSection("AppSettings")["UserPassword"];
var user = await UserManager.FindByEmailAsync(Configuration.GetSection("AppSettings")["UserEmail"]);
if (user == null)
{
var createPowerUser = await UserManager.CreateAsync(poweruser, userPassword);
if (createPowerUser.Succeeded)
{
// here we assign the new user the "Admin" role
await UserManager.AddToRoleAsync(poweruser, "SiteAdmin");
}
}
}
}
【问题讨论】:
标签: c# asp.net-core-identity asp.net-core-3.1