简体   繁体   English

如何检查用户是否有任何角色?

[英]How to check whether user has any role?

I'm currently facing an issue where I need to check if any role has been assigned to a user.我目前面临一个问题,我需要检查是否已将任何角色分配给用户。 The UserManager.IsInRoleAsync() requires a parameter that specifies the role name I want to check. UserManager.IsInRoleAsync()需要一个参数来指定我要检查的角色名称。 There's a way I can get which is fetch all roles and check one by one using for loop but it does not seem ideal to.我可以得到一种方法,即获取所有角色并使用 for 循环逐个检查,但这似乎并不理想。 Is there any ideal way to do this?有没有理想的方法来做到这一点?

Thank you.谢谢你。

You can get all the roles assigned to a user, and check if there's any.您可以获取分配给用户的所有角色,并检查是否有任何角色。 There's no need for a for loop, you just want to know that it's not empty.不需要for循环,您只想知道它不是空的。

var roles = await _userManager.GetRolesAsync(user);
var hasAnyRole = roles.Count > 0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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