Asp.net mvc自定义Filter简单使用

 自定义Filter的基本思路是继承基类ActionFilterAttribute,并根据实际需要重写OnActionExecuting,OnActionExecuted,OnResultExecuting,OnResultExecuted这四个中的一个或多个方法。

  注意类名一定要以Attribute结尾。

  故名思义,Action执行前,执行后,结果返回前,结果返回后。所以它们的执行先后顺序就是OnActionExecuting,OnActionExecuted,Action,OnResultExecuting,OnResultExecuted。

  以下是我个人在工作中的两处实际用法分享。

 一、重写OnActionExecuting,限制请求来源。

  利用最近在做微信企业号应用开发。过程中需对所有请求来源限制为只能是微信客户端。应用是基于asp.net mvc做的,所以第一反应就是借助filter过滤器实现。

  在App_Start文件夹下新建类OutOfWeiXinAttribute,并继承ActionFilterAttribute,然后重写OnActionExecuting方法。通过 Request.UserAgent中是否包含micromessenger字符标识判断请求是否来自微信客户端,最后通过filterContext.Result设置自定义返回结果。

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]就实现了想要的功能。

  #if DEBUG

  coding..

  #endif

  其中的coding 部分只有在调试环境下才会执行,所以可以用来方便调试使用。

  二、重写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]就可以了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值