Reputation: 3
I would like to control views in my action based on user roles. Roles are stored in database, I have overwritten my AuthorizeCore
to return true or false based on who is authorized to access the view. I need to know the userRole
in my controller.
How can I determine the role(s) for the current user?
[Authorize]
public ActionResult Index() {
if (userRole = "Admin") { return View("Admin");}
else {return View("Viewer");
}
Upvotes: 0
Views: 553
Reputation: 4597
Assuming your controller extends System.Web.Mvc.Controller
, then you can access the User
property on the base class. This will give you an IPrincipal
instance for the authenticated user, which includes .IsInRole(string role)
:
public ActionResult Index() {
if (User.IsInRole("Admin")) { return View("Admin");}
else {return View("Viewer");
}
Note: If your configured role provider doesn't automattically support using .IsInRole
, you can implement your own db lookups using User.Identity.Name
Upvotes: 1