首页 > Web开发 > 详细

Asp.Net Core中完成拒绝访问功能

时间:2019-09-21 17:40:34      阅读:156      评论:0      收藏:0      [点我收藏+]

 

  很多时候如果用户没有某个菜单的操作权限的话在页面是不应该显示出来的。

@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(60);
   //options.LoginPath = "/Identity/Account/Login";
    // ReturnUrlParameter requires 
    //using Microsoft.AspNetCore.Authentication.Cookies;
    options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
    options.SlidingExpiration = true;
});

 

Asp.Net Core中完成拒绝访问功能

原文:https://www.cnblogs.com/jesen1315/p/11563780.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!