asp.netasp.net-mvcrazorasp.net-identityrole-manager

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


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


Solution

  • 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.