简体   繁体   English

ASP.NET Core 2.1角色管理器注册

[英]ASP.NET Core 2.1 Role Manager Register

In my seeding code I create Users and Roles, and the error seems to be whenever I run it through startup I seem to be getting 在我的种子代码中,我创建了用户和角色,并且错误似乎是每当我通过启动运行它时,我似乎都

"No service for type Microsoft.AspNetCore.Identity.RoleManager'1[Microsoft.AspNetCore.Identity.IdentityRole] has been registered. “没有注册类型为Microsoft.AspNetCore.Identity.RoleManager'1[Microsoft.AspNetCore.Identity.IdentityRole]服务。

EDIT*** I think the issue is that the code in identityhostingstartup is not getting executed, this was created by scaffolding identity. 编辑*** 我认为问题在于, identhosthostingstartup 中的代码未得到执行,这是由脚手架标识创建的。

SeedDb.cs SeedDb.cs

public static void CreateRolesAndUsers(IServiceProvider serviceProvider)
    {
        var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
        var userManager = serviceProvider.GetRequiredService<UserManager<AppUser>>();
        var context = serviceProvider.GetService<AuthContext>();
        var configuration = serviceProvider.GetService<IConfiguration>();

        //context.Database.EnsureCreated();
        context.Database.Migrate();

        Task<IdentityResult> roleResult;
        string email = configuration["Admin:Email"];

        //Check that there is an Administrator role and create if not
        Task<bool> hasAdminRole = roleManager.RoleExistsAsync(Roles.ADMIN);
        hasAdminRole.Wait();

        if (!hasAdminRole.Result)
        {
            roleResult = roleManager.CreateAsync(new IdentityRole(Roles.ADMIN));
            roleResult.Wait();
        }

        //Check if the admin user exists and create it if not
        //Add to the Administrator role
        Task<AppUser> testUser = userManager.FindByEmailAsync(email);
        testUser.Wait();

        if (testUser.Result == null)
        {
            CreateAdminUser(userManager, email, configuration["Admin:Password"]);
        }
        else if (configuration.GetValue<bool>("Admin:Reset") == true)
        {
            userManager.DeleteAsync(testUser.Result);
            CreateAdminUser(userManager, email, configuration["Admin:Password"]);
        }

    }

    private static void CreateAdminUser(UserManager<AppUser> userManager, string email, string password)
    {
        AppUser user = new AppUser
        {
            Email = email,
            UserName = email
        };

        Task<IdentityResult> newUser = userManager.CreateAsync(user, password);
        newUser.Wait();

        if (newUser.Result.Succeeded)
        {
            Task<IdentityResult> newUserRole = userManager.AddToRoleAsync(user, Roles.ADMIN);
            newUserRole.Wait();
        }
    }

IdentityHostingStartup.cs IdentityHostingStartup.cs

enter [assembly: HostingStartup(typeof(WebApp.Areas.Identity.IdentityHostingStartup))]
namespace WebApp.Areas.Identity
{
    public class IdentityHostingStartup : IHostingStartup
    {
        public void Configure(IWebHostBuilder builder)
        {
            builder.ConfigureServices((context, services) => {
            });
        }
    }
}

Startup.cs 启动文件

 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.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(
            Configuration.GetConnectionString("DefaultConnection")));
    services.AddDefaultIdentity<IdentityUser>()
        .AddEntityFrameworkStores<ApplicationDbContext>();

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

The full error message I get is this 我得到的完整错误消息是这样

System.InvalidOperationException
  HResult=0x80131509
  Message=No service for type 'Microsoft.AspNetCore.Identity.RoleManager`1[Microsoft.AspNetCore.Identity.IdentityRole]' has been registered.
  Source=Microsoft.Extensions.DependencyInjection.Abstractions

 StackTrace:

 at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions. GetRequiredService(IServiceProvider provider, Type serviceType) 
    at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions. GetRequiredService[T](IServiceProvider provider)
   at b.Data.SeedAuth.CreateRolesAndUsers(IServiceProvider serviceProvider) in C:\Users\\source\repos\b\b\Data\SeedAuth.cs:line 17
   at b.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider) in C:\Users\\source\repos\b\b\Startup.cs:line 65

You haven't registered the role services in the DI container. 您尚未在DI容器中注册角色服务。 This line: 这行:

services.AddDefaultIdentity<AppUser>()
    .AddEntityFrameworkStores<ApplicationDbContext>();

Needs to change to include them by using the AddRoles method. 需要通过使用AddRoles方法进行更改以包括它们。 Assuming you are using the default IdentityRole class: 假设您使用默认的IdentityRole类:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM