Search code examples
asp.netasp.net-coreauthenticationroles

Asp.net 5.0 User Has Role in View


Can someone help me to understand how it works in Asp.net? How can I check the roles of the users (not logged in) in the Razor View?

Let's say a situation like this: In controller I get a list of all users:

var Users = await _context.ApplicationUser.ToListAsync()
    return View(Users);

and in View:

@foreach ( var user in Users){
if (user.IsInRole("Admin")) <---- check here if the user is in role
    { 
       do something
    }
}

How can I check if a specific role is assigned to each user?


Solution

  • You need to inject usermanager in your constructor. Then do

     await _userManager.IsInRoleAsync(user, role.Name);