ASP.NET MVC 5自定义错误页面 [英] ASP.NET MVC 5 Custom Error Page

查看:97
本文介绍了ASP.NET MVC 5自定义错误页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 ASP.NET MVC 5 应用程序中使用自定义授权属性,如下所示:

I am using a custom authorize attribute in a ASP.NET MVC 5 application like following:

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext context)
    {
        if (context.HttpContext.Request.IsAuthenticated)
        {
            context.Result = new System.Web.Mvc.HttpStatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);                
        }
        else
        {
            base.HandleUnauthorizedRequest(context);
        }
    }
}

system.web 部分提到了以下错误路径:

In system.web section of my web.config I mentioned error paths like:

<system.web>
    <customErrors mode="On" defaultRedirect="/Error/Error">
      <error statusCode="403" redirect="/Error/NoPermissions"/>
    </customErrors>
</system.web>

但是我从不重定向到 / Error / NoPermissions的自定义错误页面。相反,浏览器显示常规错误页面,显示 HTTP错误403.0-禁止访问

But I am never redirected to my custom error page at /Error/NoPermissions. Instead the browser display the general error page saying "HTTP Error 403.0 - Forbidden".

推荐答案

感谢每个人,但问题不在于403代码。其实问题出在我尝试返回403的方式上。我只是更改了代码以抛出 HttpException 而不是返回 HttpStatusCodeResult ,一切都可以使用了。我可以通过抛出 HttpException 异常返回任何HTTP状态代码,而我的 customErrors 配置可以捕获所有异常。可能是 HttpStatusCodeResult 没有按照我的预期做。

Thanks everyone, but problem is not with 403 code. Actually the problem was with the way i was trying to return 403. I just changed my code to throw an HttpException instead of returning the HttpStatusCodeResult and every things works now. I can return any HTTP status code by throwing HttpException exception and my customErrors configuration catches all of them. May be HttpStatusCodeResult is not doing the exact job I expected it to do.

我刚刚被替换

context.Result = new System.Web.Mvc.HttpStatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);

throw new HttpException((int)System.Net.HttpStatusCode.Forbidden, "Forbidden");

就是这样。

快乐的编码。

这篇关于ASP.NET MVC 5自定义错误页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆