如何检查C#当前用户角色是什么,并将其打印到屏幕上。
谢谢!
答案 0 :(得分:16)
您可以使用Roles.GetRolesForUser()
方法获取用户所属的所有rols。像这样使用它;
string[] rolesuserbelongto = Roles.GetRolesForUser();
你将拥有字符串数组中的所有角色。
您甚至可以将UserName作为参数传递,以获取该特定用户的角色,如下所示:
string[] rolesuserbelongto = Roles.GetRolesForUser("Shekhar_Pro");
答案 1 :(得分:6)
最常用的方法是获取IPrinciple,然后在其上调用IsInRole()。您如何获得原则依赖于您的运行时环境。此示例适用于在用户帐户下运行的应用。
示例:
static void PrintIsInAdministrators()
{
// There are many ways to get a principle... this is one.
System.Security.Principal.IPrincipal principle = System.Threading.Thread.CurrentPrincipal;
bool isInRole = principle.IsInRole("MyDomain\\MyRole");
Console.WriteLine("I {0} an Admin", isInRole ? "am" : "am not");
}
答案 2 :(得分:1)
Roles.GetRolesForUser();
给了我错误The Role Manager feature has not been enabled
。
如果您使用ASP.NET Identity UserManager
,可以这样理解:
var userManager = Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
var roles = userManager.GetRoles(User.Identity.GetUserId());
如果您已将用户的密钥从Guid更改为Int,例如使用以下代码:
var roles = userManager.GetRoles(User.Identity.GetUserId<int>());
答案 3 :(得分:0)
不完全确定你的问题。
你可以这样做:
this.User.IsInRole();
//loop and check whether the user is in your role.
this
对应page class,因此您只能在页面内编写上述代码,而this.User
会返回IPrincipal。
答案 4 :(得分:0)
string[] userroles = Roles.GetRolesForUser(Page.User.Identity.Name);
foreach(var role in userroles)
{
Response.Write(role);
}
答案 5 :(得分:0)
@if (Request.IsAuthenticated)
{
if (User.IsInRole("Admin"))
{
<h1> I only show this text to admin users </h1>
}
}
注意:您可以检查 AccountController.cs
文件中定义的角色(如果您已实施)。