2015-11-01 122 views
-1

如果我使用控制器級別AuthorizeAttribute拒絕/允許訪問某些資源我的代碼塊進一步回落如何確定登錄用戶的角色,就像我可以使用User.Identity.Name確定登錄的用戶名。如何確定登錄用戶角色

[Authorize(Roles="Admin, GroupA, GroupB")] 
public class MyController : Controller 
{ 
    // switch user roles here  
} 

回答

1

您可以使用Roles.GetRolesForUser(User.Identity.Name)

+0

Roles.GetRolesForUser(User.Identity.Name)將引發不設置到對象的實例異常對象引用與死亡的黃色屏幕。見下面我的實施 –

0
 [Authorize(Roles="Admin, GroupA, GroupB")] 
     public class MyController : Controller 
     { 
      public async Task<ActionResult> AddOrder(Order order) 
      { 
       var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); 

       //returns all roles for the user Id 

        var roles = await userManager.GetRolesAsync(User.Identity.GetUserId()); 

        //Additionally you may want to check the role exist 
        var roleStore = new RoleStore<IdentityRole>(new ApplicationDbContext()); 
        var roleManager = new RoleManager<IdentityRole>(roleStore); 

        bool isRoleExist = await roleManager.RoleExistsAsync("Admin");   
        return View(); 
      } 
     } 
相關問題