AspNet.Idendity: determine whether the user is in a specified Role

573 Views Asked by At

I am programming an WebApp with MVC5 and I will check if a User is in a specified Role.

Therefore I have tried to use User.IsInRole("Role") but it throws an Exception. I have tried with importing AspNet.Identity and using the User Manager but it can not find the method IsInRoleAsync(userId, role):

@using Microsoft.AspNet;
@if(UserManager.IsInRoleAsync(user.Id, "Role")){
    // some code
}

Please notice that I use it in a cshtml file and razor syntax. I hope you can help me.

Thank you in advance

2

There are 2 best solutions below

0
On BEST ANSWER

The code UserManager.IsInRoleAsync does not just work inside a Razor view (cshtml). You would have to instantiate an ApplicationUserManager instance, typically called "UserManager" as well as have a valid ApplicationUser ("user") object.

You are better off to do this work in the controller and pass it to the view with a View Model or other means like ViewBag or ViewData.

1
On

Hi you can easily do in view with the following code:

Ex: view1.cshtml

@if (Request.IsAuthenticated && User.IsInRole("Administrators"))
{
     //Any code

}