Samantha J T Star
Samantha J T Star

Reputation: 32778

How can I find out a users name and role in MVC?

Is there some way that I can find a user and user's role in MVC ? Also can a user in .Net have more than one role at once?

Upvotes: 0

Views: 90

Answers (3)

linkerro
linkerro

Reputation: 5458

Standard ASP.NET way:

  public ActionResult Test()
  {
    if (User.IsInRole("role name"))
    {
      //do something
    }
    return View();
  }

And yes, a user can be in more than one role.

Upvotes: 1

Krishanu Dey
Krishanu Dey

Reputation: 6406

Use

string username = Page.User.Identity.Name;
string[] roles =Roles.GetRolesForUser(username);  

Hope It Helps. Good Luck.

Upvotes: 3

Pravin Pawar
Pravin Pawar

Reputation: 2569

You will find the User & its role (Identity & Principle) object in HttpContext object as follows

HttpContext.User
HttpContext.User.Identity

You will have to overrider onauthorize method on basecontroller something like this

public class HomeController : Controller
    {
        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            //filterContext.HttpContext.User.Identity  
            base.OnAuthorization(filterContext);
        }
}

Upvotes: 0

Related Questions