報錯攔截過濾到error頁面
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)] public class ExceptionAttribute : FilterAttribute, IExceptionFilter { /*報錯回到報錯頁Error*/ /* *CreateTime:2013年3月18日 */ public void OnException(ExceptionContext filterContext) { //報錯回到報錯頁 string message = string.Format("消息類型:{0}<br>消息內容:{1}<br>引發異常的方法:{2}<br>引發異常源:{3}" , filterContext.Exception.GetType().Name , filterContext.Exception.Message , filterContext.Exception.TargetSite , filterContext.Exception.Source + filterContext.Exception.StackTrace ); filterContext.Controller.ViewData["ErrorMessage"] = message;//filterContext.Exception.Message + " 親!您犯錯了哦!";//得到報錯的內容 filterContext.Result = new ViewResult()//new一個url為Error視圖 { ViewName = "Error",/*在Shard文件夾下的Error.cshtml*/ ViewData = filterContext.Controller.ViewData//view視圖的屬性中的viewdata被賦值 }; filterContext.ExceptionHandled = true; } }
修改上面功能,增加ajax錯誤判斷
/*報錯回到報錯頁Error*/ /* *CreateTime:2013年3月18日 */ public void OnException(ExceptionContext filterContext) { //報錯回到報錯頁 string message = string.Format("消息類型:{0}<br>消息內容:{1}<br>引發異常的方法:{2}<br>引發異常源:{3}" , filterContext.Exception.GetType().Name , filterContext.Exception.Message , filterContext.Exception.TargetSite , filterContext.Exception.Source + filterContext.Exception.StackTrace ); filterContext.Controller.ViewData["ErrorMessage"] = message;//filterContext.Exception.Message + " 親!您犯錯了哦!";//得到報錯的內容 if (filterContext.HttpContext.Request.IsAjaxRequest()) { filterContext.Result = new ContentResult() { Content = "Error", ContentEncoding = Encoding.UTF8 }; } else { filterContext.Result = new ViewResult()//new一個url為Error視圖 { ViewName = "Error",/*在Shard文件夾下*/ ViewData = filterContext.Controller.ViewData//view視圖的屬性中的viewdata被賦值 }; } filterContext.ExceptionHandled = true; }
|
新聞熱點
疑難解答