ASP.NET Core Identity: No service for role manager

前端 未结 3 530
半阙折子戏
半阙折子戏 2021-01-01 16:10

I have an ASP.NET Core app that uses Identity. It works, but when I am trying to add custom roles to the database I run into problems.

In Startup ConfigureServ

相关标签:
3条回答
  • 2021-01-01 17:01

    This my solution seed User and Role ASP.NET Core 2.2

    Startup.cs

    services.AddDefaultIdentity<ApplicationUser>()
                .AddRoles<IdentityRole<Guid>>()
                .AddDefaultUI(UIFramework.Bootstrap4)
                .AddEntityFrameworkStores<ApplicationDbContext>();
    
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        ...
        ...
        SeedData.Initialize(app.ApplicationServices);
    )
    

    SeedData.cs

    public static void Initialize(IServiceProvider serviceProvider)
    {
        using (var scope = serviceProvider.CreateScope())
        {
            var provider = scope.ServiceProvider;
            var context = provider.GetRequiredService<ApplicationDbContext>();
            var userManager = provider.GetRequiredService<UserManager<ApplicationUser>>();
            var roleManager = provider.GetRequiredService<RoleManager<IdentityRole<Guid>>>();
    
            // automigration 
            context.Database.Migrate(); 
            InstallUsers(userManager, roleManager);
         }
     }
    
     private static void InstallUsers(UserManager<ApplicationUser> userManager, RoleManager<IdentityRole<Guid>> roleManager)
        {
            const string USERNAME = "admin@mysite.com";
            const string PASSWORD = "123456ABCD";
            const string ROLENAME = "Admin";
    
            var roleExist = roleManager.RoleExistsAsync(ROLENAME).Result;
            if (!roleExist)
            {
                //create the roles and seed them to the database
                roleManager.CreateAsync(new IdentityRole<Guid>(ROLENAME)).GetAwaiter().GetResult();
            }
    
            var user = userManager.FindByNameAsync(USERNAME).Result;
    
            if (user == null)
            {
                var serviceUser = new ApplicationUser
                {
                    UserName = USERNAME,
                    Email = USERNAME
                };
    
                var createPowerUser = userManager.CreateAsync(serviceUser, PASSWORD).Result;
                if (createPowerUser.Succeeded)
                {
                    var confirmationToken = userManager.GenerateEmailConfirmationTokenAsync(serviceUser).Result;
                    var result = userManager.ConfirmEmailAsync(serviceUser, confirmationToken).Result;
                    //here we tie the new user to the role
                    userManager.AddToRoleAsync(serviceUser, ROLENAME).GetAwaiter().GetResult();
                }
            }
        }
    
    0 讨论(0)
  • 2021-01-01 17:02

    I was having this issue

    No service for type 'Microsoft.AspNetCore.Identity.RoleManager`

    And this page was the first result on Google. It did not answer my question, so I thought I would put my solution here, for anyone else that may be having this problem.

    ASP.NET Core 2.2

    The missing line for me was .AddRoles() in the Startup.cs file.

            services.AddDefaultIdentity<IdentityUser>()
                .AddRoles<IdentityRole>()
                .AddDefaultUI(UIFramework.Bootstrap4)
                .AddEntityFrameworkStores<ApplicationDbContext>();
    

    Hope this helps someone

    Source: https://docs.microsoft.com/en-us/aspnet/core/security/authorization/roles?view=aspnetcore-2.2 (at the bottom)

    0 讨论(0)
  • 2021-01-01 17:12

    What am I doing wrong? My gut says there's something wrong with how I add the RoleManager as a service.

    The registration part is actually fine, tho' you should remove services.AddScoped<RoleManager<IdentityRole>>(), as the role manager is already added for you by services.AddIdentity().

    Your issue is most likely caused by a generic type mismatch: while you call services.AddIdentity() with IdentityRole<int>, you try to resolve RoleManager with IdentityRole, which is an equivalent of IdentityRole<string> (string being the default key type in ASP.NET Core Identity).

    Update your Configure method to take a RoleManager<IdentityRole<int>> parameter and it should work.

    0 讨论(0)
提交回复
热议问题