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

泄露秘密 提交于 2019-12-18 12:24:45

问题


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.

I see ways to check if the user is in a particular role, but I don't care what role they participate. The database will know what roles are allowed to see what data. I need to submit a collection of these roles to the data service to filter the data based on those roles.

So first step is how do I get all roles associated with the current user in a controller method?

EDIT:

This seemed to work out nicely:

Roles.GetRolesForUser(User.Identity.Name)

Supporting answers still welcome.


回答1:


Roles.GetRolesForUser(User.Identity.Name)



回答2:


This can be done with a single statement:

User.IsInRole("admin");



回答3:


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;
       }
   }
}


来源:https://stackoverflow.com/questions/6067159/asp-net-mvc-3-how-to-get-users-role-in-a-controller-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!