4

我跟隨了this post並創建了全局錯誤處理程序。我添加了自己處理404錯誤。但是,當我在本地測試時它工作正常,但一旦部署到Web服務器,我的自定義消息不再顯示。相反,默認醜陋的一個出現。爲什麼我的自定義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. 
} 

}

回答

8

你說得對,遠程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

相關問題