ASP.NET MVC 拦截器IResultFilter

在ASP.NET MVC中,有一个Result拦截器,实现ResultFilter需要继承一个类(System.Web.Mvc.FilterAttribute)和实现一个类(System.Web.Mvc.IResultFilter),

System.Web.Mvc.IResultFilter接口有两个方法:

1、OnResultExecuting方法在操作结果执行之前调用。

2、OnResultExecuted方法在在操作结果执行后调用。

下面是我测试的代码:

1、先新建一个ResultFillterAttribute类:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 
 6 namespace AttributeDemo.Common
 7 {
 8     /// <summary>
 9     /// Result拦截器
10     /// </summary>
11     public class ResultFillterAttribute : System.Web.Mvc.FilterAttribute, System.Web.Mvc.IResultFilter
12     {
13 
14         #region 执行完action后调用
15         /// <summary>
16         /// 执行完action后调用
17         /// </summary>
18         /// <param name="filterContext"></param>
19         void System.Web.Mvc.IResultFilter.OnResultExecuted(System.Web.Mvc.ResultExecutedContext filterContext)
20         {
21 
22         } 
23         #endregion
24 
25         #region 在操作结果执行之前调用
26         /// <summary>
27         /// 在操作结果执行之前调用。
28         /// </summary>
29         /// <param name="filterContext"></param>
30         void System.Web.Mvc.IResultFilter.OnResultExecuting(System.Web.Mvc.ResultExecutingContext filterContext)
31         {
32 
33         } 
34         #endregion
35 
36 
37     }
38 }

2、新建一个ResultFillterTestController控制器类,在控制器或者action写属性AttributeDemo.Common.ResultFillter,即可实现对控制器或action的结果进行拦截:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.Mvc;
 6 
 7 namespace AttributeDemo.Controllers
 8 {
 9     /// <summary>
10     /// 测试Result拦截器
11     /// </summary>
12     //[AttributeDemo.Common.ResultFillter]
13     public class ResultFillterTestController : Controller
14     {
15         //
16         // GET: /ResultFillterTest/
17 
18         [AttributeDemo.Common.ResultFillter]
19         public ActionResult TestResultFillter()
20         {
21 
22             return View();
23         }
24 
25 
26         public ActionResult Index()
27         {
28             return View();
29         }
30 
31     }
32 }
原文地址:https://www.cnblogs.com/linJie1930906722/p/5770792.html