简体   繁体   English

使用单独的类获取asp.net核心身份中的所有角色

[英]Get all roles in asp.net core identity using a separate class

I've been trying to get a list of all the roles out of asp.net core identity, This is how I've done t before using a controller: 我一直试图从asp.net核心标识中获取所有角色的列表,这是在使用控制器之前完成的工作:

public AdminController(
        UserManager<ApplicationUser> userManager,
        ILogger<AccountController> logger,
        IEmailSender emailSender,
        RoleManager<IdentityRole> roleManager,
        SignInManager<ApplicationUser> signInManager)
    {
        _userManager = userManager;
        _logger = logger;
        _emailSender = emailSender;
        _roleManager = roleManager;
        _signInManager = signInManager;
    }

private void PuplateRolesList(RegisterViewModel model)
    {
        model.Roles = _roleManager.Roles?.ToList();
    }

What I'm trying to do is have a class I can re-use that will pass back a list of all the roles and not use controller I tries this: 我想做的是有一个我可以重用的类,该类将返回所有角色的列表,而不使用控制器,我尝试这样做:

var roleStore = new RoleStore<AppRole, int, AppUserRole>(dbContext);
var roleMngr = new RoleManager<AppRole, int>(roleStore);

But in a class it obviously doesn't construct the role manager or dbContect, so i tried it myself but it doesn't work. 但是在一个类中,它显然没有构造角色管理器或dbContect,因此我自己尝试了一下,但它不起作用。 Any ideas how I can have a class in my app deliver a list or roles so I don't have it all in my controller? 关于如何在应用程序中添加类的任何想法都可以提供列表或角色,以至于我的控制器中没有全部内容?

Thanks 谢谢

Create a class: 创建一个类:

public class RoleUtility 
{
    private readonly RoleManager<IdentityRole> _roleManager;

    public RoleUtility(RoleManager<IdentityRole> roleManager)
    {
        _roleManager = roleManager;
    }

    public void PopulateRolesList(RegisterViewModel model)
    {
        model.Roles = _roleManager.Roles?.ToList();
    }
}

Extract the interface: 提取接口:

public interface IRoleUtility
{
    void PopulateRolesList(RegisterViewModel model);
}

The RoleUtility class declaration become: RoleUtility类声明变为:

public class RoleUtility: IRoleUtility

Then, in your Startup class : 然后,在您的Startup类中:

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddTransient<IRoleUtility, RoleUtility>();
}

Your controller code become: 您的控制器代码变为:

public AdminController(
        UserManager<ApplicationUser> userManager,
        ILogger<AccountController> logger,
        IEmailSender emailSender,
        IRoleUtility roleUtility,
        SignInManager<ApplicationUser> signInManager)
    {
        _userManager = userManager;
        _logger = logger;
        _emailSender = emailSender;
        _roleUtility = roleUtility;
        _signInManager = signInManager;
    }

private void PuplateRolesList(RegisterViewModel model)
    {
        _roleUtility.PopulateRolesList(model);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM