MVC 5 - Roles - IsUserInRole and Adding user to role

前端 未结 2 1471
执笔经年
执笔经年 2020-12-16 06:34

In MVC4 i used Roles.IsUserInRole to check if a given user is in some role. However, with MVC5 i can\'t do it anymore...

At first, it asked me to enable RoleManager

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-16 07:25

    The post above was really helpful (Thanks Serv, would vote up if my reputation allowed me to). It helped me solve an issue I was having with a few minor changes to fit what I was trying to achieve. My particular problem was that I wanted to check in an MVC view if the current user was in a given role group. I also found that Roles.IsUserInRole was no longer working.

    If you are doing this in a view, but using ASP.NET identity 2.0 instead of the simple membership provider offered by previous MVC versions, the following might be helpful as a 1-line solution:

    bool isAdmin = HttpContext.Current.User.IsInRole("Admin");
    

    You may then combine it with HTML to selectively show menu items (which is what I've been using it for) with something like this:

    @if (isAdmin)
    {
        
  • @Html.ActionLink("Users", "List", "Account")
  • }

    This allows me to prevent access to the user management hyperlinks where the user is not a member of the 'Admin' role.

提交回复
热议问题