简体   繁体   中英

Asp.net MVC 5 can't get user roles

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM