Reputation: 45
I recently added Identity to my ASP.NET project, but I'm having trouble checking user roles.
I originally create my Admin role in Startup.cs:
private void createRolesandUsers()
{
ApplicationDbContext context = new ApplicationDbContext();
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
if (!roleManager.RoleExists("Admin"))
{
var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
role.Name = "Admin";
roleManager.Create(role);
var user = new ApplicationUser();
user.UserName = "admin";
user.Email = "[email protected]";
string userPWD = "********";
var chkUser = UserManager.Create(user, userPWD);
if (chkUser.Succeeded)
{
var result1 = UserManager.AddToRole(user.Id, "Admin");
}
}
}
In my UserController.cs, I have a function to check if the user is an admin:
public Boolean isAdminUser()
{
if (User.Identity.IsAuthenticated)
{
var user = User.Identity;
ApplicationDbContext context = new ApplicationDbContext();
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var s = UserManager.GetRoles(user.GetUserId());
if (s[0].ToString() == "Admin")
{
return true;
}
else
{
return false;
}
}
return false;
}
However, I can't seem to find a way to access the isAdminUser() function from both my Views and my Controllers.
I've done a little bit of research the IsUserInRole() function, but when I tried:
@if (Roles.IsUserInRole(User.Identity.Name, "Admin")) { Html.ActionLink("Edit", "Edit", new { id=item.GuestID }); }
The if statement always returns false.
Upvotes: 0
Views: 345
Reputation: 7867
Try to use HttpContext.Current.User.IsInRole("Admin");
as Roles.IsUserInRole
related to old membership provider under System.Web.Security namespace and need roleManager
provider configuration in web.config
.
@if(HttpContext.Current.User.IsInRole("Admin"))
{
Html.ActionLink("Edit", "Edit", new { id = item.GuestID });
}
Another way is to use UserManager
userManager.IsInRole("userId","Admin")
Upvotes: 2