AspNetCore 2.0身份 - 注入RoleManager的问题

时间:2017-10-27 16:38:09

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

我需要为ROLES创建CRUD操作。

我收到以下错误:

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

那么,我该如何注入roleManager?

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

Class ApplicationUser

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

1 个答案:

答案 0 :(得分:3)

你应该使用.AddRoleManager&lt;&gt;而不是AddRoleStore&lt;&gt ;.或两者都是为了您想要创建新角色。 如果您不使用自定义商店,请尝试使用:AddEntityFrameworkStores

services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<YourContext>()
相关问题