ASP.NET MVC4全局过滤器

sp.Net MVC4中的全局过滤器,可以对整个项目进行全局监控。

              新建一个MVC4项目,可以在global.asax文件中看到如下代码:  FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

              表示注册全局过滤器. 

               GlobalFilters是全局过滤器的集合,可以通过add方法添加过滤器,默认情况下,HandleErrorAttribute过滤器被添加到集合中。

                接下来我们创建一个自定义过滤器,然后添加到全局过滤器集合中。

               1.创建自定义过滤器

                  创建自定义过滤器要继承ActionFilterAttribute类。我们创建一个名称为CustomerFilterAttribute的过滤器,在action里面记录下时间。

                    代码如下:

 

                  

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public class CustomerFilterAttribute : ActionFilterAttribute  
  2.   {  
  3.   
  4.       public override void OnActionExecuting(ActionExecutingContext filterContext)  
  5.       {  
  6.           base.OnActionExecuting(filterContext);  
  7.           filterContext.HttpContext.Response.Write("开始时间:"+DateTime.Now.ToString()+"<br/>");  
  8.       }  
  9.   
  10.       public override void OnActionExecuted(ActionExecutedContext filterContext)  
  11.       {  
  12.           base.OnActionExecuted(filterContext);  
  13.           var controllerName = filterContext.RouteData.Values["controller"].ToString();  
  14.           var actionName = filterContext.RouteData.Values["action"].ToString();  
  15.   
  16.           filterContext.HttpContext.Response.Write("结束时间:" + DateTime.Now.ToString() + "<br/>");  
  17.           filterContext.HttpContext.Response.Write("controller:" +controllerName+",action:"+actionName);  
  18.       }  
  19.   }  

               2.注册全局过滤器

                     过滤器创建完成后,我们把这个过滤器添加到全局过滤器中,使用  filters.Add(new CustomerFilterAttribute());方法,

                       代码如下:

                     

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public class FilterConfig  
  2.    {  
  3.        public static void RegisterGlobalFilters(GlobalFilterCollection filters)  
  4.        {  
  5.            filters.Add(new HandleErrorAttribute());  
  6.            filters.Add(new CustomerFilterAttribute());  
  7.        }  
  8.    }  

          接下来我们运行项目中的每一个页面,都会看到页面中输出时间和controller名称,效果图如下:

              

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值