Asp.Net核心MVC6如何在Identity 3中初始添加角色 [英] Asp.Net core MVC6 How to initially add roles in Identity 3
问题描述
我已经在Stackoverflow中寻找了这一点,到目前为止,在Identity中添加角色似乎有很多问题 2 ,但有所不同在身份3中.
I've looked for this in Stackoverflow and so far it appears there are plenty of questions on adding roles in Identity 1 & 2 but its different in Identity 3.
我想在数据库中植入角色.我只有两个.我打算使用已注入到类中的_roleManager.没关系.我的问题是..似乎没有任何方法可以实际添加角色..使用CreateAsync是将用户添加到角色中..如何使用"_userManager"编写代码以添加角色,还是必须这样做?另一种方式?
I want to seed roles in the database. I have just two. I intended to use _roleManager which I have injected into the class. Thats fine. My problem is.. there doesnt appear to be any method to actually add a role.. Using CreateAsync is for adding the user to the role.. how do you code to add a role using "_userManager" or do you have to do it another way?
推荐答案
编辑
身份
在 Identity
中,RoleManager
用于创建角色,而UserManager
用于将用户添加到角色.
这是为您指明正确方向的一个示例.以下代码用于创建新角色Administrator
In Identity
RoleManager
is for creating roles and UserManager
is for adding users to roles.
This is an example to point you in the right direction. The code below is for creating a new role Administrator
if (!roleManager.RoleExists("Administrator"))
{
MyIdentityRole newRole = new MyIdentityRole("Administrator", "Administrators can do something with data");
roleManager.Create(newRole);
}
编辑
此外,这是用于将用户添加到角色中,这也是一个示例:
Further, this is for adding a user to a role and this also an example:
\\assuming you test if the user has been assigned to the role "Administrator" before adding them to that role
if(RoleAdministrator == true){
userManager.AddToRole(User.Id, "Administrator");
}
这篇关于Asp.Net核心MVC6如何在Identity 3中初始添加角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!