MVC IdentityServer Db 空 Usertable/Error 播种

MVC IdentityServer Db Empty Usertable/Error seeding

我是 MVC 的新手,我的网络服务有这个问题,我似乎无法修复。 在我的 Dbinit 中,我将用户添加到用户 table 中,并将一些成分添加到我制作的成分 table 中。 将成分添加到 table 中没有任何问题。 然而,用户根本没有被添加(dbo.AspNetUsers 为空)。

当我 运行 程序时,我确实在我的初始化任务(在 DbInitializer 中)> InvalidOperationException 中收到异常,并作为错误消息 "Error Seeding Database"。这是我在 Program.cs:

中自己实现的一个异常
public static void Main(string[] args)
    {
      var host = BuildWebHost(args);

      using (var scope = host.Services.CreateScope())
      {
        var services = scope.ServiceProvider;
        try
        {
          var context = services.GetRequiredService<AppDbContext>();
          var dbInit = services.GetRequiredService<IDBInitializer>();

          dbInit.Initialize(context).GetAwaiter().GetResult();
        }
        catch (Exception ex)
        {
          var log = services.GetRequiredService<ILogger<Program>>();
          log.LogError(ex, "Error seeding Database.");
        }
       }

      host.Run();
    }

我不确定这个异常是否与我的问题有关,但我一直在尝试修复它。 我的 DbIinitializer 继承自仅包含任务定义的接口。 我在 Startup.cs 中调用了 IDBInitializer 和 DBInitializer,其中 DBInitializer 失败。 这是我的 DBInitializer 代码:

namespace mvcServer.Data
{
    public class DBInitializer : IDBInitializer
    {
      private readonly UserManager<User> userManager;
      private readonly RoleManager<IdentityRole> roleManager;

      public DBInitializer(UserManager<User> userManager, RoleManager<IdentityRole> roleManager)
      {
        this.userManager = userManager;
        this.roleManager = roleManager;
      }

    public async Task Initialize(AppDbContext context)
      {
        context.Database.EnsureCreated();

        // Look for any users
        if (context.Users.Any())
        {
          return; // Db has been seeded.
        }

      // Create roles
      await roleManager.CreateAsync(new IdentityRole("user"));

      // Populate Ingredients table
      context.Ingredients.AddRange(
        new Ingredient { Name = "Potato", Category = "Vegetable", Allergen = "Gluten", IsSafe = true },
        new Ingredient { Name = "Strawberry", Category = "Fruit", Allergen = "Sugar", IsSafe = false });

      await context.SaveChangesAsync();

        var user = new User
        {
          Name = "Andrea",
          Lastname = "X",
          AccessFailedCount = 0,
          Email = "andrea@gmail.com",
          NormalizedEmail = "ANDREA@GMAIL.COM",
          EmailConfirmed = false,
          LockoutEnabled = true,
          TwoFactorEnabled = false,
          UserName = "andrea",
          NormalizedUserName = "ANDREA"
        };

        var userResult = await userManager.CreateAsync(user, "Password123");
        var roleresult = await userManager.AddToRoleAsync(user, "user");

        if (userResult.Succeeded)
        {
          var currUser = await userManager.FindByNameAsync(user.UserName);

          // Assigns claims for security
          var claims = new List<Claim> {
                      new Claim(type: JwtClaimTypes.GivenName, value: user.Name),
                      new Claim(type: JwtClaimTypes.FamilyName, value: user.Lastname),
                  };
          await userManager.AddClaimsAsync(currUser, claims);

        }
        else
        {
          Debug.WriteLine(userResult.ToString());
        }
    }
  }
}

是否因为我使用 context.Ingredients.AddRange 而不是 Async 方法添加成分?尽管我已经尝试过了,但它什么也没做。 我也不确定在更改此类内容时是否需要丢弃我的迁移并完全重新启动。

这是Exception

System.InvalidOperationException
Message: Error seeding Database. Failed method:
Microsoft.AspNetCore.Identity.UserManager'1+<ValidateUserInternal>d_169.MoveNext

如果我需要提供更多代码或其他任何信息,请告诉我。

编辑: AppDbContext:

namespace mvcServer.Data
{
    public class AppDbContext : IdentityDbContext<User>
    {
      public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
      {
      }

    public DbSet<Ingredient> Ingredients { get; set; }
  }
}

经过大量搜索,我找到了答案,感谢 this post。

正如用户 "Daffy Punk" 在该主题中的回答:

I am leaving this here for anyone that might have had a similar issue. I had exactly the same "symptoms". It turns out that the problem related to the password being stored not adhering to the configured password policy (at least one uppercase char, one lowercase char, etc etc).

As per below comments and answers, in general, the same vague error message is thrown when any of the user creation constraints or policies are not followed.

This might include the following:

Password policy not followed (this seems to be the most common cause) Required fields being passed through as empty strings / null Duplicate username or email There is really a wide range of issues which can cause this error to occur. If the above does not solve your problem, I suggest the following:

Familiarize yourself with the rules and policies for identityprovider as it was set up for your solution As per @Ted's answer below, trace or put a breakpoint on the UserManager.Create method to view the result, as this will likely reveal the cause of your problem.

就我而言,我创建的用户密码根本不符合我设置的要求:)