MVC Learning Series-Filter Extension and mvcfilter Extension
In MVC, Filter can also be expanded. Here, I understand the Filter as AOP. I don't know any of you, so I have some high opinions...
First, four major MVC filter artifacts: IAuthorizationFilter, IActionFilter, IResultFilter, and IExceptionFilter.
Before that, install the Log4net log artifact:
Check the reference of the project.
Configuration File
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 <! -- Log Path --> 9 <param name = "File" value = "D: \ App_Log \"/> 10 <! -- Whether to append logs to the file --> 11 <param name = "AppendToFile" value = "true"/> 12 <! -- Log Retention days --> 13 <param name = "MaxSizeRollBackups" value = "10"/> 14 <! -- Whether the log file name is fixed --> 15 <param name = "StaticLogFileName" value = "false"/> 16 <! -- Log file name format: 2008-08-31.log --> 17 <param name = "DatePattern" value = "yyyy-MM-dd & quot;. log & quot;"/> 18 <! -- Rolling logs by Date --> 19 <param name = "RollingStyle" value = "Date"/> 20 <layout type = "log4net. layout. patternLayout "> 21 <param name =" ConversionPattern "value =" % d [% t] %-5 p % c-% m % n % loggername "/> 22 </layout> 23 </appender> 24 <! -- Log displayed on the console --> 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} [%-5 level] % m "/> 36 </l Ayout> 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 <! -- (High) OFF> FATAL> ERROR> WARN> INFO> DEBUG> ALL (low) --> 45 <level value = "all"/> 46 <appender-ref = "ColoredConsoleAppender"/> 47 <appender-ref = "RollingLogFileAppender"/> 48 </root> 49 </log4net> 50 <system. web> 51 <compilation debug = "true" targetFramework = "4.5.2"/> 52 Added the LogHelper help class.
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 }
Another important step is to declare in the Gobal class:
1 // load the configuration file 2 var logCfg = new FileInfo (AppDomain. CurrentDomain. BaseDirectory + "Log4Net. config"); 3 XmlConfigurator. ConfigureAndWatch (logCfg );
OK. Here, log4net is configured.
Now, I will extend the IExceptionFilter.
Create a Log4NetExceptionFilter class and inherit from the IExceptionFilter interface.
1 public class Log4NetExceptionFilter : IExceptionFilter2 {3 public void OnException(ExceptionContext filterContext)4 {5 LogHelper.WriteLog_Error(GetType(), filterContext.Exception);6 }7 }
Declare your exception handling in FilterConfig:
1 public class FilterConfig2 {3 public static void RegisterGlobalFilters (GlobalFilterCollection filters) 4 {5 // filters. add (new handleerrorattriters (); 6 // Add your own exception 7 filters. add (new Log4NetExceptionFilter (); 8} 9}
Test: manually add an exception in GetXmlResult of HomeController:
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 }
Result:
To introduce ActionFilterAttribute, there are two interfaces: IActionFilter and IResultFilter.
Therefore, the new MyActionFilterAttribute inherits from 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 }
Test: add the MyActionFilterAttribute feature to the GetXmlResult method of HomeController. Ps: The exception added manually has been removed.
[MyActionFilterAttribute] public XmlResult GetXmlResult() { StudentViewModel viewModel = new StudentViewModel(); viewModel.ID = "1"; viewModel.Name ="Zhangsan"; viewModel.Gender = "Man"; return new XmlResult(viewModel); }
Result: