11

What is the code for determining if a user is in a role?

I have set up all the users through the ASP.NET Configuration Security tab but now want to put logic around some key areas so only people in certain roles can see and access these areas.

Cœur
  • 37,241
  • 25
  • 195
  • 267
leora
  • 188,729
  • 360
  • 878
  • 1,366

4 Answers4

23
if (User.IsInRole("rolename")) {
  // my action
}
Chris Van Opstal
  • 36,423
  • 9
  • 73
  • 90
  • 3
    User is a property of the Page and HttpContext classes, so you can access it on the page simply as User, or in non-page file as HttpContext.Current.User. More info at MSDN: http://msdn.microsoft.com/en-us/library/system.web.httpcontext.user.aspx – Chris Van Opstal Jul 31 '09 at 18:08
8

Easy~

HttpContext.Current.User.IsInRole("roleName")
BigBlondeViking
  • 3,853
  • 1
  • 32
  • 28
3

Check out the Roles class, specifically IsUserInRole, GetUsersInRole, AddUserToRole, etc.

I use these all the time.

James Skemp
  • 8,018
  • 9
  • 64
  • 107
Matthew Jones
  • 25,644
  • 17
  • 102
  • 155
0

thanks to "Chris Van Opstal". i solved my problem like this way,

    public ActionResult Index()
    {

        if (User.IsInRole("Supervisor"))
        {
            return RedirectToAction("Index", "InvitationS");
        }
        return View();
    }
durlove roy
  • 229
  • 4
  • 12