gpt4 book ai didi

c# - AspNetCore 2.0 Identity - 注入(inject) RoleManager 的问题

转载 作者:太空狗 更新时间:2023-10-29 23:28:47 26 4
gpt4 key购买 nike

我需要为 ROLES 创建 CRUD 操作。

我收到以下错误:

“无法解析‘Microsoft.AspNetCore.Identity.RoleManager` 类型的服务”

那么,我该如何注入(inject) roleManager?

我正在使用 asp net core 2.0 + identity 2.2.1

类应用用户

 public class ApplicationUser : IdentityUser
{
[Key]
public override string Id { get; set; }
public bool Type { get; set; }
}

现在在 Startup.cs 中

        services.AddIdentity<ApplicationUser, IdentityRole<int>>()
.AddUserStore<UserStore<ApplicationUser, IdentityRole<int>, ApplicationDbContext, int>>()
.AddRoleStore<RoleStore<IdentityRole<int>, ApplicationDbContext, int>>()
.AddDefaultTokenProviders();

Controller

private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<IdentityUser> _roleManager;

public RolesController(UserManager<ApplicationUser> userManager, RoleManager<IdentityUser> roleManager)
{
_userManager = userManager;
_roleManager = roleManager;
}


public IActionResult Index()
{
return View(_roleManager.Roles);
}

因此,我收到错误消息:“无法解析‘Microsoft.AspNetCore.Identity.RoleManager` 类型的服务。

最佳答案

您应该使用 .AddRoleManager<> 而不是 AddRoleStore<>。或者两者都可以,以防您想创建新角色。如果您不使用自定义商店,请尝试:AddEntityFrameworkStores

services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<YourContext>()

关于c# - AspNetCore 2.0 Identity - 注入(inject) RoleManager 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46979777/

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