【问题标题】:Application_Error no longer triggers when published to IIS发布到 IIS 时不再触发 Application_Error
【发布时间】:2010-10-22 16:46:16
【问题描述】:

好的,我的 Global.asax 文件中有以下代码:

void Application_Error(object sender, EventArgs e)
{
    // Code that runs when an unhandled error occurs
        Exception objError = Server.GetLastError().GetBaseException();

        Response.Redirect(
            String.Format(
            "/Error/{0}/{1}",
            ((HttpException)objError).GetHttpCode(),
            Request.RawUrl));
}

提供整洁的错误 URL,例如“/Error/404/TheNameOfTheRequestedPage”。这在 VS 2008 中运行良好,但是一旦发布到我的本地机器,我会得到默认的错误页面:

错误摘要

HTTP 错误 404.0 - 未找到

您正在寻找的资源有 已被删除,名称已更改,或 暂时不可用

有人知道怎么做吗?我选择不使用 system.web/customErrors 因为我无法从那里访问 Server.GetLastError() (或者至少它对我没有用)并且我想获取 http 代码。

【问题讨论】:

    标签: c# asp.net iis-7.5


    【解决方案1】:

    这很可能与您触发了节点下的 web.config 中定义的 IIS Http 错误有关

    <system.webServer>    
        <httpErrors>
        </httpErrors>    
    <system.webServer>
    

    如果问题是您要返回 404 的响应代码并获取 IIS 404 页面,那么问题是您需要做的

    Response.TrySkipIisCustomErrors = true;
    

    在您让响应完成之前,否则 IIS 将拦截错误。

    这完全不直观,尤其是如果您自己设置状态代码。我试图想办法在 Microsoft Connect 上提交一个错误,即手动设置 http 错误代码不会自动设置 TrySkipIisCustomErrors,但似乎无法找出任何相关产品来提交。

    【讨论】:

      【解决方案2】:

      我遇到了类似的问题,在重定向之前调用Server.ClearError() 确实解决了问题。

      在你的情况下,我会写

      void Application_Error(object sender, EventArgs e) 
      { 
          // Code that runs when an unhandled error occurs 
              Exception objError = Server.GetLastError(); 
              if(objError is HttpException){
                //Need to clear the error, otherwise the buil-in redirect would occure
                Server.ClearError(); 
                Response.Redirect( 
                    String.Format( 
                    "/Error/{0}/{1}", 
                    ((HttpException)objError).GetHttpCode(), 
                    Request.RawUrl)); 
              }
      } 
      

      请注意,Server.GetLastError().GetBaseException() 返回 base 异常,它并不总是 HttpException,您要查找的只是 GetLastError()。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-11-01
        • 2011-10-09
        • 2011-08-02
        • 1970-01-01
        • 2016-11-12
        • 2011-06-30
        • 2011-04-12
        • 2011-09-24
        相关资源
        最近更新 更多