gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:22:49 25 4
gpt4 key购买 nike

我有一个使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com