ASP.NET核心标识:没有角色管理器的服务

Gle*_*ter 13 asp.net asp.net-core-mvc asp.net-identity-3 asp.net-core

我有一个使用Identity的ASP.NET Core应用程序.它可以工作,但是当我尝试将自定义角色添加到数据库时,我遇到了问题.

在Startup中,ConfigureServices我添加了Identity和角色管理器作为范围服务,如下所示:

services.AddIdentity<Entities.DB.User, IdentityRole<int>>()
                .AddEntityFrameworkStores<MyDBContext, int>();

services.AddScoped<RoleManager<IdentityRole>>();
Run Code Online (Sandbox Code Playgroud)

在Startup中,Configure我注入RoleManager并将其传递给我的自定义类RolesData:

    public void Configure(
        IApplicationBuilder app, 
        IHostingEnvironment env, 
        ILoggerFactory loggerFactory,
        RoleManager<IdentityRole> roleManager
    )
    {

    app.UseIdentity();
    RolesData.SeedRoles(roleManager).Wait();
    app.UseMvc();
Run Code Online (Sandbox Code Playgroud)

这是RolesData班级:

public static class RolesData
{

    private static readonly string[] roles = new[] {
        "role1",
        "role2",
        "role3"
    };

    public static async Task SeedRoles(RoleManager<IdentityRole> roleManager)
    {

        foreach (var role in roles)
        {

            if (!await roleManager.RoleExistsAsync(role))
            {
                var create = await roleManager.CreateAsync(new IdentityRole(role));

                if (!create.Succeeded)
                {

                    throw new Exception("Failed to create role");

                }
            }

        }

    }

}
Run Code Online (Sandbox Code Playgroud)

应用程序构建没有错误,但在尝试访问它时,我收到以下错误:

尝试激活'Microsoft.AspNetCore.Identity.RoleManager时无法解析类型'Microsoft.AspNetCore.Identity.IRoleStore`1 [Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole]'的服务

我究竟做错了什么?我的直觉说我将RoleManager添加为服务的方式有问题.

PS:在创建项目以从头学习身份时,我使用了"无身份验证".

Kév*_*let 16

我究竟做错了什么?我的直觉说我将RoleManager添加为服务的方式有问题.

注册部分实际上很好,你应该删除services.AddScoped<RoleManager<IdentityRole>>(),因为已经为你添加了角色管理器services.AddIdentity().

你的问题很可能造成一个泛型类型不匹配:当你打电话services.AddIdentity()IdentityRole<int>,你试图解决RoleManagerIdentityRole,这是一个相当的IdentityRole<string>(string是在ASP.NET核心身份的默认密钥类型).

更新您的Configure方法以获取RoleManager<IdentityRole<int>>参数,它应该工作.


小智 8

我有这个问题

没有针对“ Microsoft.AspNetCore.Identity.RoleManager”类型的服务

该页面是Google的第一个结果。它没有回答我的问题,所以我想将我的解决方案放在这里,以供其他可能遇到此问题的人使用。

ASP.NET Core 2.2

对我来说,缺少的行是Startup.cs文件中的.AddRoles()

        services.AddDefaultIdentity<IdentityUser>()
            .AddRoles<IdentityRole>()
            .AddDefaultUI(UIFramework.Bootstrap4)
            .AddEntityFrameworkStores<ApplicationDbContext>();
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助某人

来源:https : //docs.microsoft.com/zh-cn/aspnet/core/security/authorization/roles?view=aspnetcore-2.2(在底部)