【问题标题】:ASP.NET Core 2 seeding roles and usersASP.NET Core 2 种子角色和用户
【发布时间】:2018-02-28 20:53:11
【问题描述】:
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();

【问题讨论】:

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


【解决方案1】:

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

示例程序.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); }
        }
    }

【讨论】:

    猜你喜欢
    • 2018-08-10
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 2013-10-17
    • 2015-06-14
    • 2016-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多