没有类型 Identity.RoleManager 的服务 - Identity.IdentityRole 已注册错误

No service for type Identity.RoleManager - Identity.IdentityRole has been registered error

我是第一次使用 Microsoft Identity。我使用 IdentityUser 和 IdentityRole 配置了用户和角色。我想为 Startup.cs 中的用户分配角色。我写了一个方法来制作它

private async Task CreateUserRoles(IServiceProvider serviceProvider) {


      var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole<int>>>();
      var userManager = serviceProvider.GetRequiredService<UserManager<User>>();

      var roleName = "Super Admin";
      var roleCheck = await roleManager.RoleExistsAsync(roleName);
      if (!roleCheck) {
            Role role = new Role();
            role.Name = roleName;
            IdentityResult result = roleManager.CreateAsync(role).Result;
            //IdentityResult roleResult = await roleManager.CreateAsync(new IdentityRole<int>(roleName));
      }
      User user = new User();
      user.UserName = "someone";
      user.Password = "someone";
      user.Email = "someone@gmail.com";
      ApplicationDbContext context = new ApplicationDbContext();
      context.Users.Add(user);
      context.SaveChanges();
      user = await userManager.FindByEmailAsync("someone@gmail.com");

      await userManager.AddToRoleAsync(user, roleName);
}

但是有一个问题:

No service for type 
'Microsoft.AspNetCore.Identity.RoleManager1[Microsoft.AspNetCore.Identity.IdentityRole1[System.Int32]]' has been registered.

我该如何解决?

这是一个Startup.cs

  public class Startup {
        public Startup(IConfiguration configuration) {
              Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services) {
              services.Configure<CookiePolicyOptions>(options => {
                    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                    options.CheckConsentNeeded = context => true;
                    options.MinimumSameSitePolicy = SameSiteMode.None;
              });

              services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
              services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();


              // Add MVC services to the services container.
              services.AddMvc();
              services.AddDistributedMemoryCache(); // Adds a default in-memory implementation of IDistributedCache
              services.AddSession(opt => { opt.Cookie.IsEssential = true; });

              services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
                          .AddRazorPagesOptions(options => {
                                options.AllowAreas = true;
                                options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Settings");
                                options.Conventions.AuthorizeAreaPage("Identity", "/Account/Logout");
                          });
              services.AddDbContext<ApplicationDbContext>(options =>
                                options.UseNpgsql("User ID = postgres; Password = sa; Host = localhost; Port = 5432; Database = CCN; Pooling = true;"));

              services.ConfigureApplicationCookie(options => {
                    options.LoginPath = $"/Account/Login"; //options.LoginPath = $"/Identity/Account/Login";
                    options.LogoutPath = $"/Account/Logout";
                    options.AccessDeniedPath = $"/Account/AccessDenied";
              });



              //Password settings
              services.AddIdentity<User, Role>(o => {
                    o.Password.RequireDigit = false;
                    o.Password.RequireLowercase = false;
                    o.Password.RequireUppercase = false;
                    o.Password.RequireNonAlphanumeric = false;
                    //o.Password.RequiredLength = 3;

              }).AddEntityFrameworkStores<ApplicationDbContext>().AddRoles<IdentityRole>()
              .AddDefaultTokenProviders();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider services) {

              app.UseDeveloperExceptionPage();
              app.UseStatusCodePages();
              if (env.IsDevelopment()) {
                    app.UseDeveloperExceptionPage();
              }
              else {
                    app.UseExceptionHandler("/Home/Index");
                    app.UseHsts();
              }

              app.UseHttpsRedirection();
              app.UseStaticFiles();
              app.UseCookiePolicy();
              //Enable session 
              app.UseSession();


              app.UseAuthentication();

              app.UseMvc(routes => {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}");
              });

              //Create user role and assign it  
              CreateUserRoles(services).Wait();

        }

  }

No service for type 'Microsoft.AspNetCore.Identity.RoleManager1[Microsoft.AspNetCore.Identity.IdentityRole1[System.Int32]]' has been registered.

为 AspNetCore Identity 注册 IdentityRole 时,RoleManager<> 类型将作为 RoleManager<IdentityRole>.

注册到 ServiceCollection

每当您想要解析 RoleManager<> 时,请指定在您的启动中注册的身份角色模型作为类型参数。 将是 RoleManager<IdentityRole>你的具体情况。

在结果服务提供者上调用GetRequiredService<RoleManager<IdentityRole>>()时,GetRequiredService<RoleManager<IdentityRole>>()会抛出上述异常。

进行以下修改:

在 CreateUserRoles

var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();

在DI容器中注册角色服务(二选一)

1.Use AddIdentity()

services.AddIdentity<User, IdentityRole()
        .AddDefaultUI()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

2.Use AddDefaultIdentity ,使用 [AddRoles][1] 方法包含角色

services.AddDefaultIdentity<User>()
        .AddRoles<IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>();

参考:AddDefaultIdentity and AddIdentity

我尝试了这些解决方案,但没有用。然后我认识到我创建了一个名为 Role 的实体,它派生自 IdentityRole,其 id 数据类型为 int。我改变了

var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole<int>>>();

这一行

var roleManager = serviceProvider.GetRequiredService<RoleManager<Role>>();

这个。然后就可以了。 另一方面,感谢您的帮助!