全部,ASP.NET MVC和Ajax中的異常處理 - [HandleException]篩選器
我正在學習MVC並將其用於商業應用程序(MVC 1.0)。
我真的很努力讓我的頭在異常處理。我在網上花了很多時間,但沒有發現任何事情。
我們目前使用實現IExceptionFilter的過濾屬性。我們用這個裝飾一個基礎控制器類,這樣所有的服務器端異常都很好地路由到一個異常頁面,顯示錯誤並執行日誌記錄。
我已經開始使用返回JSON數據的AJAX調用,但是當服務器端實現拋出錯誤時,過濾器被觸發,但頁面不會重定向到Error頁面 - 它只停留在調用AJAX方法。
有沒有辦法迫使服務器上的重定向(如ASP.NET Server.Transfer的或重定向?)
我讀過,我必須返回 JSON對象(包裹.NET例外),然後在客戶端重定向,但然後我不能保證客戶端將重定向...但是(儘管我可能做錯了什麼)服務器嘗試重定向,但然後得到未經授權的異常(基本控制器是安全的,但異常控制器是不是因爲它不從它繼承)
有沒有人請有一個簡單的例子(.NET和jQuery代碼)。我覺得我在隨機希望嘗試新事物,將工作
異常到目前爲止過濾器...
public class HandleExceptionAttribute : FilterAttribute, IExceptionFilter
{
#region IExceptionFilter Members
public void OnException(ExceptionContext filterContext)
{
if (filterContext.ExceptionHandled)
{
return;
}
filterContext.Controller.TempData[CommonLookup.ExceptionObject] = filterContext.Exception;
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.Result = AjaxException(filterContext.Exception.Message, filterContext);
}
else
{
//Redirect to global handler
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = AvailableControllers.Exception, action = AvailableActions.HandleException }));
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
}
}
#endregion
private JsonResult AjaxException(string message, ExceptionContext filterContext)
{
if (string.IsNullOrEmpty(message))
{
message = "Server error"; //TODO: Replace with better message
}
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; //Needed for IIS7.0
return new JsonResult
{
Data = new { ErrorMessage = message },
ContentEncoding = Encoding.UTF8,
};
}
}
+1格雷厄姆爲我介紹TrySkipIisCustomErrors。我在絕望的搜索中找到了你的問題,我很高興我做到了。 – 2011-05-03 12:03:07
+1太多了,感謝TrySkipIisCustomErrors的提醒,這真的對我也有幫助。 – Schmuli 2012-02-06 14:15:08