自定义Filter的基本思路是继承基类ActionFilterAttribute,并根据实际须要重写OnActionExecuting,OnActionExecuted,OnResultExecuting,OnResultExecuted这四个中的一个或多个方法。html
注意类名必定要以Attribute结尾。微信
故名思义,Action执行前,执行后,结果返回前,结果返回后。因此它们的执行前后顺序就是OnActionExecuting,OnActionExecuted,Action,OnResultExecuting,OnResultExecuted。mvc
如下是我我的在工做中的两处实际用法分享。asp.net
1、重写OnActionExecuting,限制请求来源。ide
利用最近在作微信企业号应用开发。过程当中需对全部请求来源限制为只能是微信客户端。应用是基于asp.net mvc作的,因此第一反应就是借助filter过滤器实现。spa
在App_Start文件夹下新建类OutOfWeiXinAttribute,并继承ActionFilterAttribute,而后重写OnActionExecuting方法。经过 Request.UserAgent中是否包含micromessenger字符标识判断请求是否来自微信客户端,最后经过filterContext.Result设置自定义返回结果。.net
class="code_img_closed" src="/Upload/Images/2015050417/0015B68B3C38AA5B.gif" alt="" />logs_code_hide('68f63e7d-72bc-4a61-a6ce-c3a92d8609fa',event)" src="/Upload/Images/2015050417/2B1B950FA3DF188F.gif" alt="" />调试
1 /// <summary> 2 /// 防止应用程序在微信之外的地方打开 3 /// </summary> 4 public class OutOfWeiXinAttribute : ActionFilterAttribute 5 { 6 public override void OnActionExecuting(ActionExecutingContext filterContext) 7 { 8 string userAgent = filterContext.RequestContext.HttpContext.Request.UserAgent.ToLower(); 9 10 LogHelper<OutOfWeiXinAttribute>.Debug("userAgent:" + userAgent); 11 var isWeixin = userAgent.IndexOf("micromessenger") != -1; 12 13 //如下代码只会在调试时执行 14 #if DEBUG 15 isWeixin = true; 16 #endif 17 // 18 19 if (!isWeixin) 20 { 21 ViewResult view = new ViewResult(); 22 view.ViewName = "OutofWeixinApp"; 23 filterContext.Result = view; 24 } 25 else 26 { 27 base.OnActionExecuting(filterContext); 28 } 29 30 } 31 }
自定义Filter日志
在须要作此限制的Controller或者Action上直接写上[OutOfWeiXin]就实现了想要的功能。code
#if DEBUG
coding..
#endif
其中的coding 部分只有在调试环境下才会执行,因此能够用来方便调试使用。
2、重写OnActionExecuted,统一处理抛出的异常。
重写OnActionExecuted,判断filterContext.Exception是否为空,便可找到异常。设置filterContext.ExceptionHandled = true;
返回结果filterContext.Result = view;就完成了统一处理异常。
1 /// <summary> 2 /// 捕获全局异常 3 /// </summary> 4 public class LoggingFilterAttribute :ActionFilterAttribute 5 { 6 public override void OnActionExecuted(ActionExecutedContext filterContext) 7 { 8 if (filterContext.Exception != null) 9 { 10 //发送邮件并记录异常日志 11 LogHelper<LoggingFilterAttribute>.SendEmaiAndLogError(filterContext.Exception); 12 13 filterContext.Canceled = true; 14 filterContext.ExceptionHandled = true; 15 ViewResult view = new ViewResult(); 16 view.ViewName = "Error"; 17 filterContext.Result = view; 18 } 19 20 base.OnActionExecuted(filterContext); 21 } 22 }
自定义Filter处理全局异常
在须要应用的Controller或Action上写上[HandleError,LoggingFilter]就能够了。