【问题标题】:Why my custom 404 error handler does not work after deployed to web server为什么我的自定义 404 错误处理程序在部署到 Web 服务器后不起作用
【发布时间】:2013-03-26 18:53:13
【问题描述】:

我关注this post 并创建了一个全局错误处理程序。我自己添加了处理 404 错误。但是,当我在本地测试时它工作正常,但一旦部署到 Web 服务器,我的自定义消息就不再显示了。相反,会出现默认的丑陋的。

在远程调试中,我可以跟踪执行情况,它确实得到了我的自定义 404 错误操作,但不知何故,IIS 在某个时候接管了。

在我的 Global.asax.cs 中,我有:

protected void Application_Error()
{
    var exception = Server.GetLastError();
    var httpException = exception as HttpException;

    Response.Clear();
    Server.ClearError();

    var routeData = new RouteData();
    routeData.Values["controller"] = "Error";
    routeData.Values["action"] = "General";
    routeData.Values["exception"] = exception;

    Response.StatusCode = 500;

    if (httpException != null)
    {
        Response.StatusCode = httpException.GetHttpCode();

        switch (Response.StatusCode)
        {
            case 403:
                routeData.Values["action"] = "Http403";
                break;
            case 404:
                routeData.Values["action"] = "Http404";
                break;
        }
    }

    IController errorController = new ErrorController();
    var rc = new RequestContext(new HttpContextWrapper(Context), routeData);
    errorController.Execute(rc);
}

然后在我的 ErrorHandler.cs 中,我有:

public ActionResult General(Exception exception)
{
    // log error

    return Content("General error", "text/html");
}

public ActionResult Http403(Exception exception)
{
    return Content("Forbidden", "text/plain");
}

public ActionResult Http404(Exception exception)
{
    return Content("Page not found.", "text/plain"); // this displays when tested locally, but not after deployed to web server.
}

}

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-mvc-4 error-handling http-status-code-404


    【解决方案1】:

    你是对的,远程 IIS 正在接管你的 404 页面。你需要的是告诉 IIS 跳过自定义错误设置Response.TrySkipIisCustomErrors = true;

    所以你的代码应该是这样的。

    protected void Application_Error()
    {
        //...
        Response.TrySkipIisCustomErrors = true;
        Response.StatusCode = 404;
        //...rest of your code
    }
    

    还可以查看此链接以获取更多信息http://www.west-wind.com/weblog/posts/2009/Apr/29/IIS-7-Error-Pages-taking-over-500-Errors

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-25
      • 2020-05-14
      • 2016-04-19
      • 2011-06-24
      • 1970-01-01
      • 2014-04-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多