Asp.net MVC 5无法获得用户角色 [英] Asp.net MVC 5 can't get user roles

查看:71
本文介绍了Asp.net MVC 5无法获得用户角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取用户角色并对其进行修改.我尝试了多种方法来获取用户角色,但没有任何效果.有什么遗漏吗?我可以找到正确的用户实体,但角色始终为空.有什么办法可以正确地做到这一点吗?谢谢

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

这篇关于Asp.net MVC 5无法获得用户角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆