【问题标题】:Asp.net MVC Access Custom Error Page Without Authorization未经授权的 Asp.net MVC 访问自定义错误页面
【发布时间】:2016-11-22 14:09:11
【问题描述】:

在我的 Asp.Net MVC 项目中,我创建了一个自定义授权属性。如果用户未通过身份验证,我的过滤器工作正常。但是当我在我的登录页面中编写一个不存在的控制器时,我无法重定向到自定义错误页面。

这是我的自定义授权属性。

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    protected virtual CustomPrincipal CurrentUser => HttpContext.Current.User as CustomPrincipal;

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (!filterContext.HttpContext.Request.IsAuthenticated) base.OnAuthorization(filterContext);

        if (string.IsNullOrEmpty(Roles)) return;
        if (CurrentUser == null) return;
        if (!CurrentUser.IsInRole(Roles)) filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Error", action = "AccessDenied" }));
    }
}

由于我的默认路由,我的应用程序正在重定向到帐户/索引操作

    [AllowAnonymous]
    public ActionResult Index(string returnUrl) { return View(); }

    [AllowAnonymous]
    public ActionResult Index2(string systemUserId, string returnUrl)
    {

    }

    [HttpPost, ValidateAntiForgeryToken, AllowAnonymous]
    public ActionResult Index(AccountViewModel accountModel,string returnUrl)
    {

    } 

如何跳过自定义错误页面的过滤器?

【问题讨论】:

  • 澄清一下,您想为不存在的页面(控制器/操作)重定向到“拒绝访问”页面?
  • 实际上我想重定向到“未找到”视图。但我不想手动进行。我的 CustomPrinciple 中的 Roles 属性为 Null,因此 return; 命令有效。当我登录并尝试访问不存在的操作时,mvc 会处理此问题并重定向到 Notfound。
  • @YusufDuyar 你可以在 web.config <error redirect="~/Error/NotFound" statusCode="404" />

标签: asp.net asp.net-mvc


【解决方案1】:

我已将[AllowAnonymous] 属性添加到我的ErrorController 并解决了问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-28
    • 1970-01-01
    • 2011-12-02
    • 2010-12-26
    • 1970-01-01
    • 2012-06-01
    • 2014-03-31
    • 2019-07-17
    相关资源
    最近更新 更多