I'm trying to get user roles and modify it. I've tried many ways to get user roles but nothing works. Is there anything missing? I can get right User entity but Roles is always null. Is there any way to do it correctly? Thanks
我正在尝试获取用户角色并对其进行修改。我已经尝试了很多方法来获得用户角色,但没有任何作用。有什么遗漏?我可以获得正确的用户实体,但角色始终为空。有没有办法正确地做到这一点?谢谢
var user = UserManager.Users.Single(u=>u.Id==id);
var roles = user.Roles;
roles.Add(....)
var user = UserManager.Users.Single(u=>u.Id==id);
user.IsinRole("rolename");
1 个解决方案
#1
You can get them via claims:
你可以通过索赔获得它们:
var roles = ((ClaimsIdentity)User.Identity).Claims
.Where(c => c.Type == ClaimTypes.Role)
.Select(c => c.Value);
To add a user to a role, you can do (Make sure the role exists in the database though):
要将用户添加到角色,您可以这样做(确保该角色存在于数据库中):
var roleresult = UserManager.AddToRole(currentUser.Id, "RoleName");
#1
You can get them via claims:
你可以通过索赔获得它们:
var roles = ((ClaimsIdentity)User.Identity).Claims
.Where(c => c.Type == ClaimTypes.Role)
.Select(c => c.Value);
To add a user to a role, you can do (Make sure the role exists in the database though):
要将用户添加到角色,您可以这样做(确保该角色存在于数据库中):
var roleresult = UserManager.AddToRole(currentUser.Id, "RoleName");