UserManager.FindAsync始终返回null

问题描述 投票:1回答:2

我在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 = "[email protected]"
            };

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

UPDATE

在实施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 == "[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");
        }
asp.net-mvc asp.net-identity
2个回答
5
投票

FindAsync()将用户名作为第一个参数。因此,您实际上需要更改登录表单/ viewmodel以获取用户名而不是电子邮件。

标准的ASP.NET模板将用户名设置为电子邮件,这就是为什么FindAsync()使用开箱即用的电子邮件地址。所以另一种选择是做同样的事情,并在播种数据库时使用电子邮件作为用户名。


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);

现在您可以使用用户名或密码登录

© www.soinside.com 2019 - 2024. All rights reserved.