当前位置: 代码迷 >> VC/MFC >> MVC学习系列——Filter扩充
  详细解决方案

MVC学习系列——Filter扩充

热度:218   发布时间:2016-05-02 03:16:11.0
MVC学习系列——Filter扩展

     在MVC中,Filter也是可以扩展的。在此,本人对Filter的理解就是AOP,不知道各位大侠,有什么高的见解,呵呵。。。

首先MVC四大过滤神器IAuthorizationFilter,IActionFilter,IResultFilter,IExceptionFilter。

在此之前,我们先安装Log4net日志神器:

看下项目的引用

配置文件

 1 <?xml version="1.0" encoding="utf-8"?> 2 <configuration> 3   <configSections> 4     <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> 5   </configSections> 6   <log4net> 7     <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> 8       <!--日志路径--> 9       <param name= "File" value= "D:\App_Log\"/>10       <!--是否是向文件中追加日志-->11       <param name= "AppendToFile" value= "true"/>12       <!--log保留天数-->13       <param name= "MaxSizeRollBackups" value= "10"/>14       <!--日志文件名是否是固定不变的-->15       <param name= "StaticLogFileName" value= "false"/>16       <!--日志文件名格式为:2008-08-31.log-->17       <param name= "DatePattern" value= "yyyy-MM-dd&quot;.log&quot;"/>18       <!--日志根据日期滚动-->19       <param name= "RollingStyle" value= "Date"/>20       <layout type="log4net.Layout.PatternLayout">21         <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n %loggername" />22       </layout>23     </appender>24     <!-- 控制台前台显示日志 -->25     <appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">26       <mapping>27         <level value="ERROR" />28         <foreColor value="Red, HighIntensity" />29       </mapping>30       <mapping>31         <level value="Info" />32         <foreColor value="Green" />33       </mapping>34       <layout type="log4net.Layout.PatternLayout">35         <conversionPattern value="%n%date{HH:mm:ss,fff} [%-5level] %m" />36       </layout>37 38       <filter type="log4net.Filter.LevelRangeFilter">39         <param name="LevelMin" value="Info" />40         <param name="LevelMax" value="Fatal" />41       </filter>42     </appender>43     <root>44       <!--(高) OFF > FATAL > ERROR > WARN > INFO > DEBUG > ALL (低) -->45       <level value="all" />46       <appender-ref ref="ColoredConsoleAppender"/>47       <appender-ref ref="RollingLogFileAppender"/>48     </root>49   </log4net>50   <system.web>51     <compilation debug="true" targetFramework="4.5.2" />52     <httpRuntime targetFramework="4.5.2" />53   </system.web>54 </configuration>
View Code

增加LogHelper帮助类

 1  public class LogHelper 2     { 3         public static void WriteLog_Error(Type t, Exception ex) 4         { 5             log4net.ILog log = log4net.LogManager.GetLogger(t); 6             log.Error("Unhandled exception", ex); 7         } 8  9         public static void WriteLog_Error(Type t, string msg)10         {11             log4net.ILog log = log4net.LogManager.GetLogger(t);12             log.Error(msg);13         }14 15         public static void WriteLog_Info(Type t, string msg)16         {17             log4net.ILog log = log4net.LogManager.GetLogger(t);18             log.Info(msg);19         }20     }

还有一个重要的一步,在Gobal类中,要申明:

1 //加载配置文件2             var logCfg = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "Log4Net.config");3             XmlConfigurator.ConfigureAndWatch(logCfg);

ok,到这里log4net,配置完成。

 


现在,我来扩展IExceptionFilter这个过滤器。

新建Log4NetExceptionFilter类,继承接口IExceptionFilter

1 public class Log4NetExceptionFilter : IExceptionFilter2     {3         public void OnException(ExceptionContext filterContext)4         {5             LogHelper.WriteLog_Error(GetType(), filterContext.Exception);6         }7     }

在FilterConfig中申明自己的异常处理:

1  public class FilterConfig2     {3         public static void RegisterGlobalFilters(GlobalFilterCollection filters)4         {5             //filters.Add(new HandleErrorAttribute());6             //加上自己的异常7             filters.Add(new Log4NetExceptionFilter());8         }9     }

测试:在HomeController的GetXmlResult,手工增加异常:

 1  public XmlResult GetXmlResult() 2         { 3             int a = 1; 4             int b = 0; 5             int c = a / b; 6  7             StudentViewModel viewModel = new StudentViewModel(); 8             viewModel.ID = "1"; 9             viewModel.Name ="Zhangsan";10             viewModel.Gender = "Man";11 12             return new XmlResult(viewModel);13         }

结果:

 

在介绍一下ActionFilterAttribute,这个特性有两个接口IActionFilter, IResultFilter。

因此,新建MyActionFilterAttribute,继承于ActionFilterAttribute

 1 public class MyActionFilterAttribute: ActionFilterAttribute 2     { 3         public override void OnActionExecuting(ActionExecutingContext filterContext) 4         { 5             LogHelper.WriteLog_Info(GetType(), "OnActionExecuting"); 6             base.OnActionExecuting(filterContext); 7         } 8         public override void OnActionExecuted(ActionExecutedContext filterContext) 9         {10             LogHelper.WriteLog_Info(GetType(), "OnActionExecuted");11             base.OnActionExecuted(filterContext);12         }13 14         public override void OnResultExecuting(ResultExecutingContext filterContext)15         {16             LogHelper.WriteLog_Info(GetType(), "OnResultExecuting");17             base.OnResultExecuting(filterContext);18         }19 20         public override void OnResultExecuted(ResultExecutedContext filterContext)21         {22             LogHelper.WriteLog_Info(GetType(), "OnResultExecuted");23             base.OnResultExecuted(filterContext);24         }25     }

测试:在HomeController的GetXmlResult的方法上,增加MyActionFilterAttribute特性。ps:这里已经去掉刚刚手工增加的异常。

  [MyActionFilterAttribute]        public XmlResult GetXmlResult()        {            StudentViewModel viewModel = new StudentViewModel();            viewModel.ID = "1";            viewModel.Name ="Zhangsan";            viewModel.Gender = "Man";            return new XmlResult(viewModel);        }

结果:

 

  相关解决方案