首页 > 代码库 > MVC的过滤器

MVC的过滤器

过滤器分类:

Action过滤器    View结果渲染过滤器     全局错误异常过滤器    身份验证过滤器

 

1.Action过滤器:在Action执行之前和执行之后分别干一些事   接口:(IActionFilter)

2.View结果渲染过滤器:   接口:(IActionFilter)

 [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = true)]
    public class MyActionFilterAttribute :ActionFilterAttribute
    {
        public string Name { get; set; }

        //在Action执行之前先执行此方法   重写方法  执行之前先执行
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            filterContext.HttpContext.Response.Write("<br />OnActionExecuting---"+ Name);
        }
        //
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);
            filterContext.HttpContext.Response.Write("<br />OnActionExecuted---" + Name);
        }

        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            base.OnResultExecuting(filterContext);
            filterContext.HttpContext.Response.Write("<br />OnResultExecuting---" + Name);
        }

        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            base.OnResultExecuted(filterContext);
            filterContext.HttpContext.Response.Write("<br />OnResultExecuted---" + Name);
        }
    }

  怎么去调用呢?

 [MyActionFilter(Name = "Home/Index")]
        public ActionResult Index()
        {

            Response.Write("<br />Action执行了.... <br/>");
        }

   注意:类上面的标签可以作用到所有控制器上的方法

所有的控制器都需要的话(全局过滤器):

技术分享

 

 public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());

            filters.Add(new MyActionFilterAttribute(){Name = "全局的"});
        }
    }

  调用:

技术分享

控制器和类中的内容都显示:

 [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = true)]
    public class MyActionFilterAttribute :ActionFilterAttribute
    {
}

  

 

MVC的过滤器