ASP.NET Core 2播种角色和用户

时间:2017-09-19 23:29:10

标签: c# asp.net-core asp.net-core-2.0 asp.net-core-identity

public class DbInitializer 
{
    public static async Task CreateAdmin(IServiceProvider service)
    {
        UserManager<AppUser> userManager = service.GetRequiredService<UserManager<AppUser>>();
        RoleManager<IdentityRole> roleManager = service.GetRequiredService<RoleManager<IdentityRole>>();

        string username = "Admin";
        string email = "AdminG@example.com";
        string pass = "Secrete90";
        string role = "Admins";

        if(await userManager.FindByNameAsync(username)== null)
        {
            if(await roleManager.FindByNameAsync(role)== null)
            {
                await roleManager.CreateAsync(new IdentityRole(role));
            }
            var user = new AppUser { UserName = username, Email = email };

            var result = await userManager.CreateAsync(user, pass);
            if (result.Succeeded) { await userManager.AddToRoleAsync(user, role); }
        }
    }

当我在启动时运行此代码时,我收到一条错误,指出无法在启动类中调整代码的范围。

DbInitializer.CreateAdmin(app.ApplicationServices).Wait();

1 个答案:

答案 0 :(得分:1)

.NET Core 2调用您的种子逻辑需要移动到Main类的program.cs方法。

示例Program.cs

public static void Main(string[] args) {
    var host = BuildWebHost(args);
    using (var scope = host.Services.CreateScope()) {
        var services = scope.ServiceProvider;
        var userManager = services.GetRequiredService<UserManager<AppUser>>();
        var roleManager = services.GetRequiredService<RoleManager<IdentityRole>>();
        DbInitializer.CreateAdmin(userManager, roleManager).Wait();
    }
    host.Run();
}

更新了DbInitializer

public class DbInitializer 
{
    public static async Task CreateAdmin(UserManager<AppUser> userManager, RoleManager<IdentityRole> roleManager)
    {

        string username = "Admin";
        string email = "AdminG@example.com";
        string pass = "Secrete90";
        string role = "Admins";

        if(await userManager.FindByNameAsync(username)== null)
        {
            if(await roleManager.FindByNameAsync(role)== null)
            {
                await roleManager.CreateAsync(new IdentityRole(role));
            }
            var user = new AppUser { UserName = username, Email = email };

            var result = await userManager.CreateAsync(user, pass);
            if (result.Succeeded) { await userManager.AddToRoleAsync(user, role); }
        }
    }