如果我在控制器级别使用AuthorizeAttribute拒绝/允许访问某些资源,我怎样才能在代码块中进一步确定已记录的用户角色,就像我可以使用User.Identity.Name
确定记录的用户名一样。
[Authorize(Roles="Admin, GroupA, GroupB")]
public class MyController : Controller
{
// switch user roles here
}
答案 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();
}
}