ASP.NET 核心标识 : No service for role manager

标签 asp.net asp.net-core asp.net-core-mvc asp.net-identity-3

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

在启动 ConfigureServices我已将身份和角色管理器添加为这样的范围服务:

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

services.AddScoped<RoleManager<IdentityRole>>();

并在启动 Configure我注入(inject) RoleManager 并将其传递给我的自定义类 RolesData :
    public void Configure(
        IApplicationBuilder app, 
        IHostingEnvironment env, 
        ILoggerFactory loggerFactory,
        RoleManager<IdentityRole> roleManager
    )
    {

    app.UseIdentity();
    RolesData.SeedRoles(roleManager).Wait();
    app.UseMvc();

这是RolesData类(class):
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");

                }
            }

        }

    }

}

该应用程序构建时没有错误,但是在尝试访问它时出现以下错误:

Unable to resolve service for type 'Microsoft.AspNetCore.Identity.IRoleStore`1[Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole]' while attempting to activate 'Microsoft.AspNetCore.Identity.RoleManager



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

PS:我在创建项目时使用“无身份验证”从头开始学习身份。

最佳答案

我遇到了这个问题

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



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

ASP.NET 核心 2.2

对我来说缺少的行是 .AddRoles() 在 Startup.cs 文件中。
        services.AddDefaultIdentity<IdentityUser>()
            .AddRoles<IdentityRole>()
            .AddDefaultUI(UIFramework.Bootstrap4)
            .AddEntityFrameworkStores<ApplicationDbContext>();

希望这可以帮助某人

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

关于ASP.NET 核心标识 : No service for role manager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41425850/

相关文章:

asp.net - 返回时,ASP .NET Core Cookie 身份验证过期从时间戳更改为 "Session"

c# - 如何查找/呈现预编译的 Razor View

asp.net - 无法使 typeahead.js 基本示例正常工作

ASP.NET 如何从输入类型 'style' 控件中删除 ='image' 属性?

asp.net - RDLC 报告 Group By 中的列可见性问题

c# - 如何设置 if checkbox checked 语句?

asp.net-core - 如何在 OpenID (MSAL) 身份验证期间访问数据库

c# - asp.net 核心中的 csp 报告端点

asp.net-core - DependencyContext.Default 在.net core测试项目中抛出错误

c# - 为什么部署在 Azure 上的 Web 应用程序的日期格式发生变化?(ASP .NET Core)