很多时候如果用户没有某个菜单的操作权限的话在页面是不应该显示出来的。
@if (SignInManager.IsSignedIn(User) && User.IsInRole("Admin"))
{
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink"
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
管理
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" asp-controller="Admin"
asp-action="ListUsers">用户列表</a>
<a class="dropdown-item" asp-controller="Admin"
asp-action="ListRoles">角色列表</a>
</div>
</li>
}
如果通过Url来访问时,默认会跳转到一个Account/AccessDenied的拒绝页面,所以我们需要在Account控制器中定义一个AccessDenied方法,添加其视图。
[HttpGet]
[AllowAnonymous]
public IActionResult AccessDenied()
{
return View();
}
<div class="text-center">
<h1 class="text-danger">拒绝访问</h1>
<h6 class="text-danger">您没有查看此资源的权限</h6>
<img src="~/images/noaccess.png" style="height:300px; width:300px" />
</div>
当然我们可以自定义拒绝跳转页面,那就是在startup中添加 options.AccessDeniedPath ,如下:
services.ConfigureApplicationCookie(options =>
{
options.AccessDeniedPath = "/Identity/Account/AccessDenied";
//options.Cookie.Name = "YourAppCookieName";
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes();
//options.LoginPath = "/Identity/Account/Login";
// ReturnUrlParameter requires
//using Microsoft.AspNetCore.Authentication.Cookies;
options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
options.SlidingExpiration = true;
});