asp.net 身份获取登录用户的所有角色 [英] asp.net identity get all roles of logged in user

查看:70
本文介绍了asp.net 身份获取登录用户的所有角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个基于角色的菜单,我遵循了教程.在该页面的下方,您会看到以下代码行:

I created a role based menu for which I followed this tutorial. Some where down that page you'll see this line of code:

String[] roles = Roles.GetRolesForUser();

它返回当前登录用户的所有角色.我想知道如何使用新的 ASP.NET Identity 系统来实现这一点?

It returns all roles of the currently logged in user. I was wondering how to accomplish this with the new ASP.NET Identity system?

它仍然很新,关于它的信息不多.

It's still pretty new and there is not much to find about it.

推荐答案

Controller.User.Identity 是一个 ClaimsIdentity.您可以通过检查声明来获取角色列表...

Controller.User.Identity is a ClaimsIdentity. You can get a list of roles by inspecting the claims...

var roles = ((ClaimsIdentity)User.Identity).Claims
                .Where(c => c.Type == ClaimTypes.Role)
                .Select(c => c.Value);

--- 更新---

再分解一下...

using System.Security.Claims;

// ........

var userIdentity = (ClaimsIdentity)User.Identity;
var claims = userIdentity.Claims;
var roleClaimType = userIdentity.RoleClaimType;
var roles = claims.Where(c => c.Type == ClaimTypes.Role).ToList();

// or...
var roles = claims.Where(c => c.Type == roleClaimType).ToList();

这篇关于asp.net 身份获取登录用户的所有角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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