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

InitializeIdentityForEF freezes and does not create the default admin account

刚开始做项目的时候没有报错

现在,当我 运行 项目并创建数据库时,它会不断加载和加载。如果我停止并再次 运行,一切正常,只是我的管理员帐户未创建。

我正在使用 Identity 2.0。

代码如下:

 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);
        }
    }

遇到了同样的问题,OWIN 当时还没有准备好。假设 ApplicationDbContext 派生自 Identity Context,请为经理尝试此代码:

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

Understanding MVC-5 Identity