InitializeIdentityForEF冻结并且不会创建默认管理员帐户

时间:2022-11-07 04:05:27

When I first started the project, I had no errors.

当我第一次启动项目时,我没有错误。

Now, when I run the project and it creates the database, it keeps loading and loading. If I stop and run again, everything works fine, except my admin account was not created.

现在,当我运行项目并创建数据库时,它会继续加载和加载。如果我停止并再次运行,一切正常,除了我的管理员帐户没有创建。

I'm using Identity 2.0.

我正在使用Identity 2.0。

Here is the code:

这是代码:

 public static void InitializeIdentityForEF(ApplicationDbContext db) {
        var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
        var roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>();
        const string name = "admin@mundogato.org";
        const string password = "Admin@1234";
        const string roleName = "Admin";

        //Create Role Admin if it does not exist
        var role = roleManager.FindByName(roleName);
        if (role == null) {
            role = new ApplicationRole(roleName);
            var roleresult = roleManager.Create(role);
        }

        var user = userManager.FindByName(name);
        if (user == null) {
            user = new ApplicationUser { UserName = name, Email = name };
            var result = userManager.Create(user, password);
            result = userManager.SetLockoutEnabled(user.Id, false);
        }

        // Add user admin to Role Admin if not already added
        var rolesForUser = userManager.GetRoles(user.Id);
        if (!rolesForUser.Contains(role.Name)) {
            var result = userManager.AddToRole(user.Id, role.Name);
        }
    }

1 个解决方案

#1


Had the same issue where OWIN wasn't ready at that point. Try this code for the managers, assuming ApplicationDbContext derives from the Identity Context:

那个OWIN还没有做好相同的问题。假设ApplicationDbContext派生自身份上下文,请为管理器尝试此代码:

var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db));
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));

See Understanding MVC-5 Identity

请参阅了解MVC-5身份

#1


Had the same issue where OWIN wasn't ready at that point. Try this code for the managers, assuming ApplicationDbContext derives from the Identity Context:

那个OWIN还没有做好相同的问题。假设ApplicationDbContext派生自身份上下文,请为管理器尝试此代码:

var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db));
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));

See Understanding MVC-5 Identity

请参阅了解MVC-5身份