根据用户角色显示或隐藏导航菜单

image.png

  1. @if (SignInManager.IsSignedIn(User) && User.IsInRole("Admin"))
  2. {
  3. <li class="nav-item">
  4. <a class="nav-link" asp-controller="Admin" asp-action="ListRoles">角色管理</a>
  5. </li>
  6. }

默认的拒绝访问地址是 AccessDenied:
http://localhost:3290/Account/AccessDenied?ReturnUrl=%2FAdmin%2FListRoles

  1. [HttpGet]
  2. [AllowAnonymous]
  3. public IActionResult AccessDenied()
  4. {
  5. return View();
  6. }

AccessDenied 页面:

  1. @{
  2. ViewBag.Title = "拒绝访问";
  3. }
  4. <div class="text-center">
  5. <h1 class="text-danger">拒绝访问</h1>
  6. <h6 class="text-danger">您没有查看此资源的权限</h6>
  7. <img src="~/images/noaccess.png" style="width: 300px; height: 300px;" />
  8. </div>

image.png

自定义拒绝访问地址

也可以在 ConfigureServices 里面自定义拒绝访问的地址:

  1. services.ConfigureApplicationCookie(options =>
  2. {
  3. options.AccessDeniedPath = "/Account/Fangyu";
  4. });

此时访问拒绝地址就会变成 Fangyu:
http://localhost:3290/Account/Fangyu?ReturnUrl=%2FAdmin%2FListRoles