Inside the scaffolded partial view _Layout.cshtml
is defined the app's navigation bar. I'd like to modify it so that some links are only shown if the logged user is "Admin"
.
Inside the Seed()
method of my Configuration.cs
file for migrations, is defined the following:
bool AddUserAndRole(ApplicationDbContext context) {
IdentityResult ir;
var rm = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
ir = rm.Create(new IdentityRole("Admin"));
var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var user = new ApplicationUser() { UserName = "admin", FirstName = "System", LastName = "Administrator" };
ir = um.Create(user, "admin");
if(ir.Succeeded == false) {
return ir.Succeeded;
}
ir = um.AddToRole(user.Id, "Admin");
return ir.Succeeded;
}
As you can see, there is a role called "Admin" and the newly created user is added to that role.
That being said, I've tried several ways inside my _Layout.cshmtl
to attempt to determine whether the current user is "Admin"
or not
@if(Roles.IsUserInRole(User.Identity.Name, "Admin")) { }
@if (User.IsInRole("Admin")) { }
but none seem effective. How do I do that?
@if (User.IsInRole("Admin"))
{
<li>@Html.ActionLink("Link Text", "Controller", "Action")</li>
}
This worked for me.