MVC下的全局異常過濾器註冊方式以下:標紅爲asp.net mvc ,asp.net mvc api 註冊全局異常過濾器的不一樣之處json
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">上下文對象</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文件。api