【问题标题】:AspNetCore 2.0 Identity - Issues with injecting RoleManagerAspNetCore 2.0 Identity - 注入 RoleManager 的问题
【发布时间】:2018-02-15 02:57:48
【问题描述】:

我需要为 ROLES 创建 CRUD 操作。

我收到以下错误:

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

那么,我该如何注入 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();

控制器

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` 的服务。

【问题讨论】:

    标签: c# asp.net-core asp.net-core-identity


    【解决方案1】:

    您应该使用 .AddRoleManager 而不是 AddRoleStore。如果您想创建新角色,或者两者兼而有之。 如果您不使用自定义商店,请尝试:AddEntityFrameworkStores

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

    【讨论】:

      猜你喜欢
      • 2014-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-21
      • 2018-07-07
      • 2014-06-30
      • 2015-10-09
      • 1970-01-01
      相关资源
      最近更新 更多