.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的好。

posted @ 2016-12-29 14:04  1+1剑锋  阅读(1745)  评论(0编辑  收藏  举报