>Like ,
用户管理器。AddUserToRole(userrole.用户标识,用户角色。角色标识(;
我被困在这里,任何人都可以帮助将用户添加到特定公司的特定角色(多租户(
下面是一个关于如何向用户添加角色的简单演示:
1.控制器:
public class HomeController : Controller
{
private readonly RoleManager<IdentityRole> _roleManager;
private readonly UserManager<IdentityUser> _userManager;
public HomeController(RoleManager<IdentityRole> roleManager, UserManager<IdentityUser> userManager)
{
_roleManager = roleManager;
_userManager = userManager;
}
public async Task CreateRolesandUsers()
{
bool x = await _roleManager.RoleExistsAsync("Admin");
if (!x)
{
// first we create Admin role
var role = new IdentityRole();
role.Name = "Admin";
await _roleManager.CreateAsync(role);
}
//Then we create a user
var user = new IdentityUser();
user.UserName = "default";
user.Email = "default@default.com";
string userPWD = "122@Xsdf";
IdentityResult chkUser = await _userManager.CreateAsync(user, userPWD);
//Add default User to Role Admin
if (chkUser.Succeeded)
{
var result = await _userManager.AddToRoleAsync(user, "Admin");
}
}
}
2.启动.cs:
services.AddIdentity<IdentityUser, IdentityRole>()
//services.AddDefaultIdentity<IdentityUser>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultUI()
.AddDefaultTokenProviders();
在这种情况下,解决方案是添加带有角色表 (n-n( 的租户表映射。客户端查询用户信息时,先检查租户,然后再将用户信息与角色映射