欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

asp.net mvc ,asp.net mvc api 中使用全局过滤器进行异常捕获记录

程序员文章站 2022-06-11 22:42:09
...

MVC下的全局异常过滤器注册方式如下:标红为asp.net mvc ,asp.net mvc api  注册全局异常过滤器的不同之处

using SuperManCore;
using System.Web;
using System.Web.Mvc;
namespace SuperMan
{
    public class FilterConfig
    {
        /// <summary>
        /// 注册全局过滤器 add by caoheyang 20150205
        /// </summary>
        /// <param name="filters"></param>
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new WebHandleErrorAttribute(), 1);
            filters.Add(new HandleErrorAttribute(), 2);
        }
    }
    /// <summary>
    /// 自定义异常处理类  add by caoheyang 20150205
    /// </summary>
    public class WebHandleErrorAttribute : HandleErrorAttribute
    {
        /// <summary>
        /// 重写异常处理方法 add by caoheyang 20150205   需要将该特性标注于各个controller上。
        /// </summary>
        /// <param name="filterContext">上下文对象  该类继承于ControllerContext</param>
        public override void OnException(ExceptionContext filterContext)
        {
            LogHelper.LogWriterFromFilter(filterContext.Exception);
        }
    }
}

  

MVC API下的注册方式如下:
在WebApiConfig.cs文件下加入标红代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using Microsoft.Owin.Security.OAuth;
using Newtonsoft.Json.Serialization;
namespace SuperManWebApi
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API 配置和服务
            // 将 Web API 配置为仅使用不记名令牌身份验证。
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
            config.Filters.Add(new ApiHandleErrorAttribute());  //注册全局异常过滤器 add by caoheyang 20150206     不需要将该特性标注于各个controller上
            // Web API 路由
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",                
                routeTemplate: "{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}
 /// <summary> /// 自定义异常处理类 add by caoheyang 20150205 不需要将该特性标注于各个controller上。 /// </summary> public class ApiHandleErrorAttribute : ExceptionFilterAttribute { /// <summary> /// 重写异常处理方法 add by caoheyang 20150205 /// </summary> /// <param name="filterContext">上下文对象 该类继承于ControllerContext</param> public override void OnException(HttpActionExecutedContext filterContext) { LogHelper.LogWriterFromFilter(filterContext.Exception); }
}

  

另外附LogHelper源码:
public class LogHelper
    {
       public static Logger logger = LogManager.GetLogger("SuperManCore.LogHelper");
       /// <summary>
       /// 备注日志
       /// </summary>
       /// <param name="dec">需要捕获的参数(必须为属性类)</param>
       /// <param name="rmark">描述操作</param>
       public new static void LogWriter(string rmark="",object dec=null)
       {
           try
           {
               string logstr = "\r\n-----------------start----------------------\r\n";
               MethodBase m = new StackTrace().GetFrame(1).GetMethod();
               ParameterInfo[] pm = m.GetParameters();
               string classname = m.DeclaringType.ToString();
               string propertyName = m.Name;
               logstr = logstr + "备注:" + rmark + "\r\n";
               //写类名
               logstr = logstr + "函数类名:" + classname + "\r\n";
               //写函数方法
               logstr = logstr + "函数名称为:" + propertyName + "\r\n";
               for (int i = 0; i < pm.Length; i++)
               {
                   logstr = logstr + "函数的参数有:" + pm[i].Name.ToString() + "\r\n";
               }
               JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
               logstr = logstr + "函数参数值:" + jsonSerializer.Serialize(dec) + "\r\n";
               logstr += "--------------------end---------------------\r\n";
               //写日志
               logger.Info(logstr);
           }
           catch (Exception)
           {
               throw;
           }
       }  
       /// <summary>
       /// 异常捕获日志
       /// </summary>
       /// <param name="ex">异常对象(必须为属性类)</param>
       /// <param name="rmark">操作简要描述</param>
       public new static void LogWriter(Exception ex, string rmark="")
       {
           try
           {
               string logstr = "\r\n-----------------start----------------------\r\n";
               MethodBase m = new StackTrace().GetFrame(1).GetMethod();
               ParameterInfo[] pm = m.GetParameters();
               string classname = m.DeclaringType.ToString();
               string propertyName = m.Name;
               logstr = logstr + "备注:" + rmark + "\r\n";
               //写类名
               logstr = logstr + "函数类名:" + classname + "\r\n";
               //写函数方法
               logstr = logstr + "函数名称为:" + propertyName + "\r\n";
               for (int i = 0; i < pm.Length; i++)
               {
                   logstr = logstr + "函数的参数有:" + pm[i].Name.ToString() + "\r\n";
               }
               logstr = logstr + "函数异常:" + ex.ToString() + "\r\n";
               logstr += "--------------------end---------------------\r\n";
               //写日志
               logger.Info(logstr);
           }
           catch (Exception)
           {
               throw;
           }
       }
       /// <summary>
       /// 带参数 异常的日志
       /// </summary>
       /// <param name="dec">异常参数对象(必须为属性类)</param>
       /// <param name="ex">日志异常对象</param>
       public new static void LogWriter(object dec, Exception ex)
       {
           try
           {
               string logstr = "\r\n-----------------start----------------------\r\n";
               MethodBase m = new StackTrace().GetFrame(1).GetMethod();
               ParameterInfo[] pm = m.GetParameters();
               string classname = m.DeclaringType.ToString();
               string propertyName = m.Name;
               //写类名
               logstr = logstr + "函数类名:" + classname + "\r\n";
               //写函数方法
               logstr = logstr + "函数名称为:" + propertyName + "\r\n";
               for (int i = 0; i < pm.Length; i++)
               {
                   logstr = logstr + "函数的参数有:" + pm[i].Name.ToString() + "\r\n";
               }
               JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
               logstr = logstr + "函数参数值:" + jsonSerializer.Serialize(dec) + "\r\n";
               logstr = logstr + "函数异常:" + ex.ToString() + "\r\n";
               logstr += "--------------------end---------------------\r\n";
               //写日志
               logger.Info(logstr);
           }
           catch (Exception)
           {
               throw;
           }
       }
       /// <summary>
       /// 带参数 描述 异常日志捕获
       /// </summary>
       /// <param name="dec">所要捕获的参数(必须为属性类)</param>
       /// <param name="ex">异常对象</param>
       /// <param name="rmark">描述</param>
       public new static void LogWriter(object dec, Exception ex, string rmark)
       {
           try
           {
               string logstr = "\r\n-----------------start----------------------\r\n";
               MethodBase m = new StackTrace().GetFrame(1).GetMethod();
               ParameterInfo[] pm = m.GetParameters();
               string classname = m.DeclaringType.ToString();
               string propertyName = m.Name;
               //写备注
               logstr = logstr + "备注:" + rmark + "\r\n";
               //写类名
               logstr = logstr + "函数类名:" + classname + "\r\n";
               //写函数方法
               logstr = logstr + "函数名称为:" + propertyName + "\r\n";
               for (int i = 0; i < pm.Length; i++)
               {
                   logstr = logstr + "函数的参数有:" + pm[i].Name.ToString() + "\r\n";
               }
               JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
               logstr = logstr + "函数参数值:" + jsonSerializer.Serialize(dec) + "\r\n";
               logstr = logstr + "函数异常:" + ex.ToString() + "\r\n";
               logstr += "--------------------end---------------------\r\n";
               //写日志
               logger.Info(logstr);
           }
           catch (Exception)
           {
               throw;
           }
       }
       /// <summary>
       /// 捕获全局异常
       /// </summary>
       /// <param name="error"></param>
       public new static void LogWriterFromFilter(Exception error)
       {
           try
           {
               string logstr = "\r\n-----------------start----------------------\r\n"; 
               //异常发生地址
               logstr = logstr + "异常发生地址:" + HttpContext.Current.Request.Url.AbsoluteUri.ToString() + "\r\n";
               logstr = logstr + "请求类型:" + HttpContext.Current.Request.RequestType.ToString() + "\r\n";
               logstr = logstr + "异常:" + error.ToString() + "\r\n";
               logstr += "--------------------end---------------------\r\n";
               //发送邮件
               if (ConfigSettings.Instance.IsSendMail == "true")
               {
                   string emailToAddress = ConfigSettings.Instance.EmailToAdress;
                   EmailHelper.SendEmailTo(logstr, emailToAddress);
               }              
               //写日志
               logger.Info(logstr);
           }
           catch (Exception)
           {
               throw;
           } 
       }
    }

注:LogHelper所在类库需要引用NLog.dll文件。