2014-10-01 112 views
1

我對a有以下的登錄操作,而UserManager.FindAsync總是返回空值。我正在嘗試使用底部顯示的代碼對用戶進行種子處理。UserManager.FindAsync總是返回null

任何人都可以幫忙嗎?

public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) 
    { 
     if (ModelState.IsValid) 
     { 
      var user = await UserManager.FindAsync(model.Email, model.Password); 
      if (user != null) 
      { 
       await SignInAsync(user, model.RememberMe); 
       return RedirectToLocal(returnUrl); 
      } 
      else 
      { 
       ModelState.AddModelError("", "Invalid username or password."); 
      } 
     } 

     // If we got this far, something failed, redisplay form 
     return View(model); 
    } 

我在Configuration.cs下有M​​igrations下面的一段代碼。它所做的是爲我嘗試使用上面的代碼登錄的用戶創建一個用戶。

protected override void Seed(Temps.Models.ApplicationDbContext context) 
    { 
     if (!context.Roles.Any(r => r.Name == "Consultant")) 
     { 
      var store = new RoleStore<IdentityRole>(context); 
      var manager = new RoleManager<IdentityRole>(store); 
      var role = new IdentityRole { Name = "Consultant" }; 

      manager.Create(role); 
     } 

     if (!context.Users.Any(u => u.UserName == "Consultant")) 
     { 
      var store = new UserStore<ApplicationUser>(context); 
      var manager = new UserManager<ApplicationUser>(store); 
      var user = new ApplicationUser 
      { 
       UserName = "Consultant", 
       Email = "[email protected]" 
      }; 

      manager.Create(user, "password"); 
      manager.AddToRole(user.Id, "Consultant"); 
     } 

UPDATE

實施安東尼的變化,我得到以下錯誤下面的種子代碼,任何想法後?

PM> Update-database 指定'-Verbose'標誌來查看應用於目標數據庫的SQL語句。 沒有待處理的顯式遷移。 運行種子法。 System.InvalidOperationException:找不到UserId。 在Microsoft.AspNet.Identity.UserManager 2.<AddToRoleAsync>d__83.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNet.Identity.AsyncHelper.RunSync[TResult](Func 1個FUNC) 在Microsoft.AspNet.Identity.UserManagerExtensions.AddToRole [TUSER,TKEY的]在System.Data.Entity.Migrations.DbMigrator(的UserManager 2 manager, TKey userId, String role) at Temps.Migrations.Configuration.Seed(ApplicationDbContext context) in c:\Work\@wandc\Temps\trunk\src\Temps\Migrations\Configuration.cs:line 67 at System.Data.Entity.Migrations.DbMigrationsConfiguration 1.OnSeed(的DbContext上下文) .SeedDatabase() 在System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.SeedDatabase() 在System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable的1 pendingMigrations, String targetMigrationId, String lastMigrationId) at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable 1 pendingMigrations,字符串targetMigrationId,字符串lastMigrationId) 在系統。 Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration) at System.Data.Entity.Migrations.DbMigrator。<> c__DisplayClassc.b__b() at System.Data.Entity.Mi grations.DbMigrator.EnsureDatabaseExists(動作mustSucceedToKeepDatabase) 在System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(動作mustSucceedToKeepDatabase) 在System.Data.Entity.Migrations.DbMigrator.Update(字符串targetMigration) 在System.Data .Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration) at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.Run() at System.AppDomain System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate) 。 DoCallBack(CrossAppDomainDelegate callBackDelegate) at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner) at System.Data.Entity.Migrations.Design.ToolingFacade.Update(String targetMigration,布爾力) 在System.Data.Entity.Migrations.UpdateDatabaseCommand。 <> c__DisplayClass2。 < .ctor> b__0() at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command) UserId not found。

代碼:

 if (!context.Users.Any(u => u.UserName == "[email protected]")) 
     { 
      string emailAddress = "[email protected]"; 

      var store = new UserStore<ApplicationUser>(context); 
      var manager = new UserManager<ApplicationUser>(store); 
      var user = new ApplicationUser() 
      { 
       UserName = emailAddress, 
       Email = emailAddress, 
       FirstName = "Admin", 
       LastName = "Admin", 
       PasswordHint = password 
      }; 

      manager.Create(user, password);     
      manager.AddToRole(user.Id, "Admin"); 
     } 

回答

4

FindAsync()採用用戶名作爲第一個參數。所以你實際上需要改變登錄表單/ viewmodel來取用戶名而不是電子郵件。

標準的ASP。NET模板將用戶名設置爲電子郵件,這就是爲什麼FindAsync()使用開箱即用的電子郵件地址。因此,另一種選擇是在種子數據庫時做同樣的事情並使用電子郵件作爲用戶名。

+0

感謝安東尼登錄實施變更,現在我得到上述錯誤? – Burt 2014-10-01 16:18:50

+0

在添加到角色之前檢查'manager.Create(user,password)'的返回值是否成功。我的猜測是用戶創建出了問題,可能密碼不夠強。 (也,很好的密碼提示:)。 – 2014-10-01 16:30:16

+0

:)只有在最初測試時纔會將所有內容都丟棄並重新加載到實時環境中(我希望) – Burt 2014-10-01 16:34:39

4

以上答案幫助我構建了這一個。

 if (ModelState.IsValid) 
     { 
      IOwinContext context = Request.GetOwinContext(); 



      var user = await UserManager.FindAsync(model.Email, model.Password); 
      var u = await UserManager.FindByEmailAsync(model.Email); 
      bool passhash = false; 
      if (u != null) 
      { 
       passhash = await UserManager.CheckPasswordAsync(u, model.Password); 
      } 
      //ApplicationUser user = await repo.FindUser(model.Email, model.Password); 
      if (user != null) 
      { 
       await SignInAsync(user, model.RememberMe); 
       return RedirectToLocal(returnUrl); 
      } 
      else if (u != null && passhash) 
      { 
       await SignInAsync(u, model.RememberMe); 
       return RedirectToLocal(returnUrl); 
      } 
      else 
      { 
       ModelState.AddModelError("", "Invalid username or password."); 
      } 
     } 

     // If we got this far, something failed, redisplay form 
     return View(model); 

現在你可以用用戶名或密碼