zoukankan      html  css  js  c++  java
  • .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的好。

  • 相关阅读:
    CentOS7中安装Mysql5.7
    CentOS7安装JDK
    设计模式之策略模式
    jmeter:文件下载连接请求保存文件
    pytest框架
    jmeter:设置全局默认请求
    jmeter:全局设置变量参数
    Badboy报错:不支持XXX属性、方法
    jmeter配置元器件:CSV Data Set Config
    jmeter报错:java.lang.IllegalArgumentException: Filename must not be null or empty
  • 原文地址:https://www.cnblogs.com/wgale025/p/6232759.html
Copyright © 2011-2022 走看看