.NET MVC Filter異常處理


 MVC程序中自帶的HandleErrorAttribute,來處理異常,不在顯示黃頁。前提是在web.config 中 system.web中關閉customerError選項。

但是很多情況下調試異常的時候,我們都希望知道用戶當時提交的數據及請求的URL地址。在WebForm時代要處理這個挺費勁的。在MVC中處理起來真簡單。

開工,自定義AppErrorAttribute類,繼承HandleErrorAttribute,然后重寫父類的OnException方法。

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改成我們自己定義的。

public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new AppErrorAttribute());
        }
    }

哦了。出現異常,發現日志都已經被記錄下來了。相應的參數都有了。這下調試找問題太方便了

哎,沒有經歷webform的痛,怎么會知道mvc的好。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM