加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – 为什么我的自定义404错误处理程序在部署到Web服务器

发布时间:2020-12-16 07:19:11 所属栏目:asp.Net 来源:网络整理
导读:我跟着 this post创建了一个全局错误处理程序.我自己添加了处理404错误.但是,当我在本地测试时它工作正常但是一旦部署到Web服务器,我的自定义消息就不再显示了.相反,默认丑陋的显示. 在远程调试中,我可以跟踪执行情况,它确实可以实现我的自定义404错误操作,
我跟着 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.
}

}

解决方法

你是对的,远程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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读