通过重写OnException方法形式实现。
1、自定义异常记录类并继承HandleErrorAttribute类。
public class HandlerErrorAttribute : HandleErrorAttribute { public override void OnException(ExceptionContext context) { base.OnException(context); //context.ExceptionHandled = true; WriteLog(context); var url = context.HttpContext.Request.Path; var msg = url + context.Exception.Message; new LogApp().WriteDbLog(msg); } private void WriteLog(ExceptionContext context) { if (context == null) return; var log = LogFactory.GetLogger(context.Controller.ToString()); log.Error(context.Exception); } }
2、修改原有FilterConfig文件,使其添加新添加的HandlerErrorAttribute类。
public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandlerErrorAttribute()); } }
3、Global.asax中注册(默认已注册过滤器)。
public class MvcApplication : System.Web.HttpApplication { /// <summary> /// 启动应用程序 /// </summary> protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); } }