ASP.NET MVC 3: How to get User's Role in a Controller Method?

后端 未结 3 907
醉梦人生
醉梦人生 2020-12-30 04:16

I want to be able to

  1. Get a list of roles of the current authenticated user.
  2. Filter the data provided to that user based on their role.

相关标签:
3条回答
  • 2020-12-30 04:42
    Roles.GetRolesForUser(User.Identity.Name)
    
    0 讨论(0)
  • 2020-12-30 04:43

    This can be done with a single statement:

    User.IsInRole("admin");
    
    0 讨论(0)
  • 2020-12-30 04:52

    If anyone need this information, in case your user has many roles but you're looking for one, you could do this:(i thought id share)

    @if (Request.IsAuthenticated)
    {
       string[] roles = Roles.GetRolesForUser();
       foreach (string role in roles)
       {
           if (role.Contains("admin"))
           {
               <li>@Html.ActionLink("Administration", "Admin", "Movies")</li>
               break;
           }
       }
    }
    
    0 讨论(0)
提交回复
热议问题