2015-05-07 30 views
0

當我第一次啓動項目時,我沒有錯誤。InitializeIdentityForEF凍結並且不會創建默認管理帳戶

現在,當我運行該項目並創建數據庫時,它會繼續加載和加載。如果我停下來再運行,一切正常,除非我的管理員帳戶沒有被創建。

我正在使用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 = "[email protected]"; 
     const string password = "[email protected]"; 
     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); 
     } 
    } 

回答

2

有同樣的問題,即OWIN不準備在這一點上。嘗試爲管理者這段代碼,假設ApplicationDbContext從標識上下文推導:

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

Understanding MVC-5 Identity

相關問題