ASP.NET MVC check if user belongs to [x] group

nathanchere picture nathanchere · Jan 14, 2010 · Viewed 12.9k times · Source

Maybe I'm approaching this the wrong way and should be doing everything in action filters, in which case please point me in the right direction!

I'm setting up my ASP.NET MVC application so that the one HomeController Index action delivers two different types of content, like so:

if(Request.IsAuthenticated)
  return View("IndexRegistered");
else
  return View("IndexGuest");

This is fine but say I want to split it into three so Administrator members get their own page...

if(Request.IsAuthenticated)
{
  if( /* user is a member of administrators */)
    return View("IndexAdministrator");
  else
    return View("IndexCustomer");
}
else
  return View("IndexGuest");

Can someone enlighten me as to the missing piece of this puzzle?

Answer

user434917 picture user434917 · Jan 14, 2010

Use the Roles property of the Authorize Action Filter:

[Authorize(Roles="Administrators,Moderators")]
public ActionResult SomeAction(){

}

Or use the User.IsInRole() method:

if(User.IsInRole("Administrator")) { ... }