toofun
toofun

Reputation: 25

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

Upvotes: 0

Views: 576

Answers (2)

Karthik Elumalai
Karthik Elumalai

Reputation: 1612

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

Ex: view1.cshtml

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

}

Upvotes: 2

travis.js
travis.js

Reputation: 5281

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.

Upvotes: 1

Related Questions