【问题标题】:InitializeIdentityForEF freezes and does not create the default admin accountInitializeIdentityForEF 冻结并且不创建默认管理员帐户
【发布时间】:2015-05-07 19:51:03
【问题描述】:

当我第一次开始这个项目时,我没有任何错误。

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

我正在使用 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);
        }
    }

【问题讨论】:

    标签: asp.net asp.net-mvc entity-framework asp.net-identity


    【解决方案1】:

    遇到了同样的问题,当时 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      • 2016-05-09
      • 1970-01-01
      • 2019-12-19
      • 2019-12-12
      • 1970-01-01
      相关资源
      最近更新 更多