2013-02-27 62 views
1

我已經在MVC(4)中設置了錯誤處理,並且它工作得很好。我在global.asax中註冊了HandleErrorAttribute,並在web.config中設置了適當的配置。 但是,如果我重定向到錯誤視圖並且錯誤視圖本身會引發錯誤,那麼我會無休止地重定向到錯誤頁面。錯誤發生在應用程序之外管理的佈局和佈局中。如果佈局中存在錯誤,我會調整。我怎樣才能防止這一點?我應該使用什麼樣的錯誤處理回退?使用不同的佈局不是一種選擇。Asp.Net MVC:在錯誤視圖中引發處理錯誤

+0

當視圖中的錯誤發生時,您能調試並驗證'Application_Error'是否在global.asax中被命中? – mattytommo 2013-02-27 19:19:46

回答

1

以下是我的操作方法。試試看:

protected void Application_Error(object sender, EventArgs e) 
{       
    //Retrieving the last server error 
    var exception = Server.GetLastError();  

    //Erases any buffered HTML output 
    Response.Clear(); 

    //Declare the exception 
    var httpException = exception as HttpException; 

    var routeData = new RouteData(); 
    routeData.Values.Add("controller", "Error"); //Adding a reference to the error controller 

    if (httpException == null) 
    { 
     routeData.Values.Add("action", "ServerError"); //Non HTTP related error handling 
    } 
    else //It's an Http Exception, Let's handle it. 
    { 
     switch (httpException.GetHttpCode()) 
     { 
      //these are special views to handle each error 
      case 401: 
      case 403: 
       //Forbidden page. 
       routeData.Values.Add("action", "Forbidden"); 
       break; 
      case 404: 
       //Page not found. 
       routeData.Values.Add("action", "NotFound"); 
       break;  
      case 500: 
       routeData.Values.Add("action", "ServerError"); 
       break; 
      default: 
       routeData.Values.Add("action", "Index"); 
       break; 
     } 
    } 

    //Pass exception details to the target error View. 
    routeData.Values.Add("message", exception); 

    //Clear the error on server. 
    Server.ClearError(); 

    //Avoid IIS7 getting in the middle 
    Response.TrySkipIisCustomErrors = true; 

    // Call target Controller and pass the routeData. 
    IController errorController = new ErrorController(); 
    errorController.Execute(new RequestContext(
     new HttpContextWrapper(Context), routeData)); 
}   
+0

我花了一個下午找出一個錯誤,直到我發現'Response.TrySkipIisCustomErrors = true;'修復。 – Graham 2013-02-27 20:43:07

+0

感謝您的迴應艾哈邁德!如果ServerError操作引發異常,會發生什麼情況? – Joe 2013-03-02 01:19:52

+0

對格雷厄姆:我也曾發生過這樣的事情:) – Joe 2013-03-02 01:20:40