UserManager.FindAsync总是返回null
我对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下有Migrations下面的一段代码。它所做的是为我尝试使用上面的代码登录的用户创建一个用户。
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");
}
FindAsync()
采用用户名作为第一个参数。所以你实际上需要改变登录表单/ viewmodel来取用户名而不是电子邮件。
标准的ASP。NET模板将用户名设置为电子邮件,这就是为什么FindAsync()
使用开箱即用的电子邮件地址。因此,另一种选择是在种子数据库时做同样的事情并使用电子邮件作为用户名。
以上答案帮助我构建了这一个。
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);
现在你可以用用户名或密码
感谢安东尼登录实施变更,现在我得到上述错误? – Burt 2014-10-01 16:18:50
在添加到角色之前检查'manager.Create(user,password)'的返回值是否成功。我的猜测是用户创建出了问题,可能密码不够强。 (也,很好的密码提示:)。 – 2014-10-01 16:30:16
:)只有在最初测试时才会将所有内容都丢弃并重新加载到实时环境中(我希望) – Burt 2014-10-01 16:34:39