我在a上有以下登录操作,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中有以下代码。它的作用是为我尝试使用上面的代码登录的用户播种。
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 = "consultant@temps-ltd.co.uk"
};
manager.Create(user, "password");
manager.AddToRole(user.Id, "Consultant");
}
更新
在实施Anthony的更改后,我对下面的种子代码,任何想法都会出现以下错误?
PM> Update-database
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
No pending explicit migrations.
Running Seed method.
System.InvalidOperationException: UserId not found.
at Microsoft.AspNet.Identity.UserManager2.<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](Func1 func)
at Microsoft.AspNet.Identity.UserManagerExtensions.AddToRole[TUser,TKey](UserManager2 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.DbMigrationsConfiguration1.OnSeed(DbContext context)
at System.Data.Entity.Migrations.DbMigrator.SeedDatabase()
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.SeedDatabase()
at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration)
at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClassc.<Update>b__b()
at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)
at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.Run()
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
at System.Data.Entity.Migrations.Design.ToolingFacade.Update(String targetMigration, Boolean force)
at 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 == "admin@temps-ltd.co.uk"))
{
string emailAddress = "admin@temps-ltd.co.uk";
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");
}
答案 0 :(得分:5)
FindAsync()
将用户名作为第一个参数。因此,您实际上需要更改登录表单/ viewmodel以获取用户名而不是电子邮件。
标准ASP.NET模板将用户名设置为电子邮件,这就是为什么FindAsync()
使用开箱即用的电子邮件地址的原因。所以另一个选择是做同样的事情,并在播种数据库时使用电子邮件作为用户名。
答案 1 :(得分: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);
现在您可以使用用户名或密码登录