如何确定记录的用户角色

时间:2015-11-01 20:25:19

标签: c# .net asp.net-mvc

如果我在控制器级别使用AuthorizeAttribute拒绝/允许访问某些资源,我怎样才能在代码块中进一步确定已记录的用户角色,就像我可以使用User.Identity.Name确定记录的用户名一样。

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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();
            }
        }