AspNetCore 2.0身份-注入RoleManager的问题 [英] AspNetCore 2.0 Identity - Issues with injecting RoleManager

查看:298
本文介绍了AspNetCore 2.0身份-注入RoleManager的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为ROLES创建CRUD操作.

I need to create CRUD operations for ROLES.

我遇到以下错误:

无法解析类型为'Microsoft.AspNetCore.Identity.RoleManager'的服务"

"Unable to resolve service for type 'Microsoft.AspNetCore.Identity.RoleManager`"

那么,我该如何注入roleManager?

So, how can i inject roleManager?

我正在使用asp net core 2.0 +身份2.2.1

I'm using asp net core 2.0 + identity 2.2.1

Class ApplicationUser

Class ApplicationUser

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

现在在Startup.cs中

Now in 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`的服务.

And so, i get error: "Unable to resolve service for type 'Microsoft.AspNetCore.Identity.RoleManager`.

推荐答案

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

You should use .AddRoleManager<> instead of AddRoleStore<>. Or both in case you want to create new roles. If you are not using custom stores try with: AddEntityFrameworkStores

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

这篇关于AspNetCore 2.0身份-注入RoleManager的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆