ASP.NET MVC 中的过滤器

  1. ActionFilter 方法过滤器:
      接口名为 IActionFilter ,在控制器方法调用前/后执行。

在新建的MVC程序中,添加一个类 MyFilter1Attribute 并继承ActionFilterAttribute抽象类

从上图可以看到 ActionFilterAttribute 中的所有方法,且有相应的介绍,我们可以通过继承 ActionFilterAttribute 类,并重写(override)它的方法,从而实现自定义Filter

复制代码
   public class MyFilter1Attribute: ActionFilterAttribute
{
///
/// 该方法会在Action方法执行之前调用
///
///
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.HttpContext.Response.Write(“我是OnActionExecuting,我在Ation方法调用前执行
”);
base.OnActionExecuting(filterContext);
}

    /// <summary>
    /// 该方法会在Action方法执行之后调用
    /// </summary>
    /// <param name="filterContext"></param>
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        filterContext.HttpContext.Response.Write("我是OnActionExecuted,我在Action方法调用后执行<br/>");
        base.OnActionExecuted(filterContext);
    }

}

复制代码
然后创建一个HomeController控制器,并添加FilterTest的测试Action

复制代码
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}

    [MyFilter1]
    public void FilterTest()
    {
        Response.Write("我是Action方法,我在这里执行了.....<br/>");
    }
}

复制代码
运行程序并访问FilterTest方法:

上图可看出它的一个执行顺序

但是有时候也有可能有这样的场景:当检查到Action有标识某个Attribute的时候,我们需要跳出,并不执行后续的方法的情况,我们可以通过filterContext中ActionDescriptior类中的IsDefained方法进行判断检查

复制代码
     ///
/// 该方法会在Action方法执行之前调用
///
///
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.HttpContext.Response.Write(“我是OnActionExecuting,我在Ation方法调用前执行
”);
//判断Action方法时是否有贴上MyFilter1Attribute标签
if (filterContext.ActionDescriptor.IsDefined(typeof(MyFilter1Attribute), false))
{
//如果有,为该Action方法直接返回ContentResult,则该Action方法在这里就有了返回值,相当于在这里就结束了,不会再去执行之后的方法,例如:OnActionExecuted
filterContext.Result = new ContentResult();
}
base.OnActionExecuting(filterContext);
}
深圳网站建设www.sz886.com

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值