2011-08-18 61 views
3

當發生錯誤時,爲什麼自定義錯誤頁面將與下面的ajax響應一起發送?在ASP.NET MVC 3中使用Ajax響應發送自定義錯誤頁面

響應

{"Errors":["An error has occurred and we have been notified. We are sorry for the inconvenience."]}<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8" /> 
    <title>Error</title> 

的Web.Config

<customErrors defaultRedirect="Error" mode="On"></customErrors> 

BaseController.cs

public class BaseController : Controller 
    { 
     protected override void OnException(ExceptionContext filterContext) 
     { 
      if (filterContext.HttpContext.Request.IsAjaxRequest()) 
      { 
       var response = filterContext.HttpContext.Response; 

       var validatorModel = new ValidatorModel(); 

       if (filterContext.Exception is AriesException && !((AriesException)filterContext.Exception).Visible && filterContext.HttpContext.IsCustomErrorEnabled) 
       { 
        validatorModel.Errors.Add(this.Resource("UnknownError")); 
       } 
       else 
       { 
        validatorModel.Errors.Add(filterContext.Exception.Message); 
       } 

       response.Clear(); 
       response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError; 
       response.Write(validatorModel.ToJson()); 
       response.ContentType = "application/json"; 
       response.TrySkipIisCustomErrors = true; 
       filterContext.ExceptionHandled = true; 
       System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest(); 
      } 
      else if (filterContext.HttpContext.IsCustomErrorEnabled) 
      { 
       filterContext.ExceptionHandled = true; 
      } 

      if(filterContext.ExceptionHandled) 
      { 
       SiteLogger.Write(filterContext.Exception); 
      } 
     } 


    } 

回答

0

我添加到Response.End();它的工作。有沒有更好的辦法?

4

在任何人的情況下仍然有這個問題,我找到了一個稍微清晰的解決方案:

if (!filterContext.HttpContext.Request.IsAjaxRequest()) 
{ 
     //non-ajax exception handling code here 
} 
else 
{ 
     filterContext.Result = new HttpStatusCodeResult(500); 
     filterContext.ExceptionHandled = true; 
} 
2

dsomuah的解決方案是好的,但必須添加到每個供應Ajax請求控制器。我們把它更進一步,在全球註冊了以下行動過濾器:

public class HandleAjaxErrorAttribute : HandleErrorAttribute 
{ 
    public override void OnException(ExceptionContext filterContext) 
    { 
     if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest()) 
     { 
      filterContext.ExceptionHandled = true; 
      filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError; 
      filterContext.HttpContext.Response.StatusDescription = filterContext.Exception.Message; 
     } 
    } 
} 
+0

雖然dsomuah的代碼可以很容易地進入你的控制器基類,因爲很多項目已經實現了由於種種原因,它很高興看到這裏列出此方法。 +1 – shannon

相關問題