【问题标题】:ASP.NET MVC 5 - return special error page instead of custom error pageASP.NET MVC 5 - 返回特殊错误页面而不是自定义错误页面
【发布时间】:2018-10-17 14:10:14
【问题描述】:

我不完全确定我的问题的标题。我需要为常见错误(404、500 等)设置自定义错误页面,但我还需要针对特定​​错误使用自己的“特殊”错误页面。

我配置了由 IIS 提供的自定义错误页面,如下所示,它工作正常。发生了一些事情,引发了错误 500,并提供了 /Error/InternalServerError 并保留了原始 URL。

但是如果我访问/Error/Special 我有问题。如果我将状态码设置为 500,我将获得错误页面 /Error/InternalServerError 的内容而不是内容 /Error/Special 的状态码为 500。由于 web.configTrySkipIisCustomErrors = true 无法正常工作。

我的 web.config 中有这个:

<httpErrors errorMode="Custom" existingResponse="Replace">
  <clear/>
  <error statusCode="500" path="/Error/InternalServerError" responseMode="ExecuteURL" />
</httpErrors>

还有这个控制器:

public class ErrorController : Controller
{
    // special error page
    public ActionResult Special()
    {
        //Response.StatusCode = (int)HttpStatusCode.InternalServerError; // <- I cant set status code because IIS returns error page (custom error page) instead
        //Response.TrySkipIisCustomErrors = true; // <- needs httpErrors - existingResponse="Passthrough" but custom error pages are not working with it
        return View();
    }

    public ActionResult InternalServerError()
    {
        Response.StatusCode = (int)HttpStatusCode.InternalServerError;
        return View();
    }
}

为什么我需要“特殊”错误页面?我想做这样的事情:

public class SpecialController : Controller
{      
    public SpecialController()
    {
        // something
    }

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);

        if ( something != true )
        {
            // it would be nice to do it without redirect, just return /Error/Special and stop executing original request
            filterContext.Result = new RedirectToRouteResult(
                        new RouteValueDictionary
                        {
                            { "action", "Special" },
                            { "controller", "Error" }
                        });
        }
    }
}

我错过了什么吗?

【问题讨论】:

    标签: c# asp.net-mvc web-config custom-error-pages custom-errors


    【解决方案1】:

    我认为这个博客可以帮助你。几年前它为我做过。

    http://benfoster.io/blog/aspnet-mvc-custom-error-pages

    【讨论】:

    • 请说得更具体一些。如您所见,我的自定义错误页面正常工作。但我有不同的问题,我需要为特定操作禁用自定义错误页面并稍后使用该操作。
    • 也许您可以生成自定义错误代码并将该代码重定向到特定控制器?例如 999 然后重定向到您的控制器
    • 我不认为“发明”HTTP 状态码是正确的方法,即使它可以工作 - 网络浏览器会得到未知的状态码。
    • 是的,如果您遵守 RFC 1xx:信息 - 已收到请求,继续处理 2xx:成功 - 操作已成功接收、理解并接受 3xx:重定向 - 必须采取进一步措施为了完成请求 4xx:客户端错误 - 请求包含错误的语法或无法满足 5xx:服务器错误 - 服务器未能满足明显有效的请求 [1]:
    • [RFC 2616][1]:“HTTP 状态码是可扩展的。HTTP 应用程序不需要理解所有已注册状态码的含义,尽管这种理解显然是可取的。但是,应用程序必须理解任何状态码的类别,由第一个数字表示,并将任何无法识别的响应视为等同于该类别的 x00 状态码
    猜你喜欢
    • 2014-06-27
    • 2015-11-14
    • 1970-01-01
    • 2011-04-20
    • 2014-11-09
    • 2018-12-03
    • 2020-11-16
    • 2014-05-10
    • 1970-01-01
    相关资源
    最近更新 更多