2013-02-27 99 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