I am trying to manipulate an Asp.Net web app's navigation based on roles.
I have created an Asp.Net (6.0 LTS) Web App with role based authentication based on Microsoft.AspNetCore.Identity. I am able to control access to (Razor)Pages as well as limit acces to not logged in users.
Program.cs
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = false)
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
Page.cshtml.cs
using Microsoft.EntityFrameworkCore;
using ...;
namespace ...
{
[Authorize(Roles = "Admin")]
public class IndexModel : PageModel
{...
The check if a user is logged in or not on the navigation level works as follows:
_LoginPartial.cshtml
@if (SignInManager.IsSignedIn(User))
{
...
}
else
{
...
}
My question: How can I manipluate this _LoginPartial.cshtml subpage based on roles? Why show navigation items to users that can not use them in the first place?
Thanks :)
CodePudding user response:
You can use the IsInRole
method:
@if (User.IsInRole("Admin"))
{
...
}
else
{
...
}