I have the following Login action on a and the UserManager.FindAsync always returns null. I am trying to seed the users with the code shown at the bottom.
Can anyone help please?
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);
}
I have the following bit of code for in the Configuration.cs under Migrations. What it does is seed a user that I am trying to log in with the code above.
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
After implementing Anthony's changes I get the following error for the seed code below, any ideas?
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.
Code:
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() takes the username as the first parameter. So you would actually need change the login form/viewmodel to take a username instead of an email.
The standard ASP.NET template sets the username to the email, that's why FindAsync() works with an email address out of the box. So another option is to do the same thing and use the email as the username when seeding the database.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With