MVC程序中自帶的HandleErrorAttribute,來處理異常,不在顯示黃頁。前提是在web.config 中 system.web中關閉customerError選項。web
可是不少狀況下調試異常的時候,咱們都但願知道用戶當時提交的數據及請求的URL地址。在WebForm時代要處理這個挺費勁的。在MVC中處理起來真簡單。mvc
開工,自定義AppErrorAttribute類,繼承HandleErrorAttribute,而後重寫父類的OnException方法。ide
public class AppErrorAttribute: HandleErrorAttribute { public override void OnException(ExceptionContext filterContext) { base.OnException(filterContext); if (!filterContext.ExceptionHandled) { string ControllerName = string.Format("{0}Controller", filterContext.RouteData.Values["controller"] as string); string ActionName = filterContext.RouteData.Values["action"] as string; NameValueCollection gets = filterContext.HttpContext.Request.QueryString; List<string> listget = new List<string>(); foreach( string key in gets) { listget.Add( string.Format("{0}={1}",key,gets[key]) ); } NameValueCollection posts = filterContext.HttpContext.Request.Form; List<string> listpost = new List<string>(); if (filterContext.HttpContext.Request.Files.Count <=0) { foreach (string key in posts) { listpost.Add(string.Format("{0}={1}", key, posts[key])); } } string ErrorMsg = string.Format("在執行 controller[{0}] 的 action[{1}] 時產生異常。get參數:{2},post參數:{3}", ControllerName, ActionName, string.Join("&",listget.ToArray()),string.Join("&",listpost.ToArray())); Utils.Common.Log4NetHelper.Error(ErrorMsg, filterContext.Exception);//用Log4net記錄日誌 } } }
而後修改App_Start中的FilterConfig.cs。把以前註冊的Filter改爲咱們本身定義的。post
public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new AppErrorAttribute()); } }
哦了。出現異常,發現日誌都已經被記錄下來了。相應的參數都有了。這下調試找問題太方便了spa
哎,沒有經歷webform的痛,怎麼會知道mvc的好。調試