c# - MVC IdentityServer Db 空用户表/错误播种

标签 c# asp.net-mvc asp.net-core-identity

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

当我运行该程序时,我确实在我的初始化任务(在 DbInitializer 中)> InvalidOperationException 中遇到异常,并作为错误消息“错误播种数据库”。这是我自己在 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 继承自仅包含任务定义的接口(interface)。 我在 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

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

编辑: 应用程序数据库上下文:

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

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

最佳答案

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

正如用户“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.

在我的例子中,我创建的用户密码根本不符合我设置的要求:)

关于c# - MVC IdentityServer Db 空用户表/错误播种,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47485403/

相关文章:

c# - .NET(或 MFC)的高速绘图控件?

c# - Crystal 报表询问用户名和密码

c# - 有没有办法找到特定层中的每个 RigidBody?

asp.net-mvc - SignalR 客户端 - 远程服务器返回错误(401 未经授权)

.net - 使用 .Net MVC 3 在 ViewModel 中验证当前密码以更改密码的最佳实践?

c# - 将 DataGrid 转换为 DataTable

asp.net-core-2.0 - asp.net 核心身份 - Id 列是 nvarchar(450) - 为什么?

c# - 如何在Azure函数中绑定(bind)到MessageSender?

c# - GitHub 上是否提供适用于 ASP .Net Core 3.1 的 ChangePasswordAsync?

asp.net-core - ForbidAsync 与 ChallengeAsync 为什么以及何时使用它们