【问题标题】:ASP.NET MVC: How to show a specific view as result of failed authorization in IAuthorizationFilterASP.NET MVC:如何在 IAuthorizationFilter 中显示授权失败的特定视图
【发布时间】:2011-09-22 11:09:55
【问题描述】:

我有检查特定角色的 IAuthorizationFilter 过滤器。如果用户没有指定的角色,我想显示一个特定的视图,上面写着“您没有权限查看此页面”。

我还想在特定的 url 上显示这个视图,所以重定向不是一个选项。

这就是我想要的:

1) 用户转到 /Admin/Payments 2) /Admin/Payments 需要管理员权限 3) 用户不是管理员。 4) 用户显示页面显示他无法访问此页面,但 url 是 /Admin/Payments

谢谢。

【问题讨论】:

    标签: asp.net-mvc action-filter


    【解决方案1】:
    public class MyAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
        {
            // TODO: do your authorization or if you want to keep the default
            // simlpy invoke the base method
        }
    
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            filterContext.Result = new ViewResult
            {
                ViewName = "~/Views/Shared/Unauthorized.cshtml"
            };
        }
    }
    

    然后:

    [MyAuthorize(Roles = "Admin")]
    public ActionResult Payments()
    {
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 2013-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-29
      相关资源
      最近更新 更多