2011-01-31 94 views

回答

15

您可以使用Roles.GetRolesForUser()方法來獲取所有rols用戶所屬的。像這樣使用它;

string[] rolesuserbelongto = Roles.GetRolesForUser(); 

您將擁有字符串數組中的所有角色。

你甚至可以通過一個用戶名作爲參數,以獲得角色像這樣的特定用戶:

string[] rolesuserbelongto = Roles.GetRolesForUser("Shekhar_Pro"); 
+0

什麼命名空間有添加爲了有「角色」類? – Ixtlan 2013-04-20 22:54:43

0

不能完全確定的你的問題。

你可以這樣做:

this.User.IsInRole(); 
//loop and check whether the user is in your role. 

this可能符合page class,這樣你就可以只寫頁面內上面的代碼和this.User返回IPrincipal

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"); 
    } 
0
string[] userroles = Roles.GetRolesForUser(Page.User.Identity.Name); 
foreach(var role in userroles) 
{ 
Response.Write(role); 
} 
0

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>()); 
相關問題