英文:
How to add user to role using UserId and RoleId of Asp.net core identity
问题
我卡在这里,有人可以帮忙将用户添加到特定公司的特定角色(多租户)吗?
英文:
Like ,
usermanager.AddUserToRole(userrole.UserId, userrole.RoleId);
I am stucked here, Can anyone please help to add user to specific Role of a specific Company (Multi tenancy)
答案1
得分: 3
以下是关于如何向用户添加角色的简单演示:
- 控制器(Controller):
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)
{
// 首先,我们创建管理员角色
var role = new IdentityRole();
role.Name = "Admin";
await _roleManager.CreateAsync(role);
}
// 然后,我们创建一个用户
var user = new IdentityUser();
user.UserName = "default";
user.Email = "default@default.com";
string userPWD = "122@Xsdf";
IdentityResult chkUser = await _userManager.CreateAsync(user, userPWD);
// 将默认用户添加到Admin角色
if (chkUser.Succeeded)
{
var result = await _userManager.AddToRoleAsync(user, "Admin");
}
}
}
- 启动文件(Startup.cs):
services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultUI()
.AddDefaultTokenProviders();
请注意,这些代码片段是关于如何在ASP.NET Core中向用户添加角色的演示,它们包含了创建角色、创建用户以及将用户添加到角色的步骤。
英文:
Here is a simple demo about how to add role to user:
1.Controller:
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.Startup.cs:
services.AddIdentity<IdentityUser, IdentityRole>()
//services.AddDefaultIdentity<IdentityUser>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultUI()
.AddDefaultTokenProviders();
答案2
得分: 0
在这种情况下,解决方案是将租户表与角色表添加为映射关系(n-n)。当客户查询用户信息时,请在将用户信息与角色映射之前检查租户。
英文:
In this case, the solution is adding a tenant table map with the role table (n-n). When clients query userInfo, check tenant before map userInfo with roles
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论