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");
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");
来源:https://stackoverflow.com/questions/30094754/asp-net-mvc-5-cant-get-user-roles