如何在ASP.NET Core中创建角色并将其分配给用户? [英] How to create roles in ASP.NET Core and assign them to users?
本文介绍了如何在ASP.NET Core中创建角色并将其分配给用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用ASP.NET Core默认网站模板,并将身份验证选择为个人用户帐户".如何创建角色并将其分配给用户,以便可以使用控制器中的角色来过滤访问权限?
I am using the ASP.NET Core default website template and have the authentication selected as "Individual User Accounts". How can I create roles and assign it to users so that I can use the roles in a controller to filter access?
推荐答案
我已经在 Accounts
控制器中创建了一个动作,该动作调用一个函数来创建角色并分配 Admin 代码>角色作为默认用户.(您可能应该删除生产环境中的默认用户):
I have created an action in the Accounts
controller that calls a function to create the roles and assign the Admin
role to the default user. (You should probably remove the default user in production):
private async Task CreateRolesandUsers()
{
bool x = await _roleManager.RoleExistsAsync("Admin");
if (!x)
{
// first we create Admin rool
var role = new IdentityRole();
role.Name = "Admin";
await _roleManager.CreateAsync(role);
//Here we create a Admin super user who will maintain the website
var user = new ApplicationUser();
user.UserName = "default";
user.Email = "default@default.com";
string userPWD = "somepassword";
IdentityResult chkUser = await _userManager.CreateAsync(user, userPWD);
//Add default User to Role Admin
if (chkUser.Succeeded)
{
var result1 = await _userManager.AddToRoleAsync(user, "Admin");
}
}
// creating Creating Manager role
x = await _roleManager.RoleExistsAsync("Manager");
if (!x)
{
var role = new IdentityRole();
role.Name = "Manager";
await _roleManager.CreateAsync(role);
}
// creating Creating Employee role
x = await _roleManager.RoleExistsAsync("Employee");
if (!x)
{
var role = new IdentityRole();
role.Name = "Employee";
await _roleManager.CreateAsync(role);
}
}
您可以创建一个控制器来管理用户角色.
After you could create a controller to manage roles for the users.
这篇关于如何在ASP.NET Core中创建角色并将其分配给用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文