MVC过滤器之结果过滤器

结果过滤器属性提供了两个事件会在运行检视(ActionResult,ExecutrResult)的前后运行,分别是OnResultExecuting与OnResultExecuted事件,属性类别实作IResultFilter界面会被要求必须实作这两个方法。

由于从Action回传的ActionResult一定有个ExecuteResult方法用来运行检视的结果,所以,通过这个过滤器可以在运行之前整理一些信息给ActionResult使用,或在运行之后对结果进行,最常见的例子就是实作输出缓存机制,Asp.net MVC 内建的属性有OutPutCache属性。

来个实例:

以下是演示将Guest这个Action 的输出结果缓存120秒:

  [OutputCache(Duration = 120, VaryByCustom = "CityChannel")]
        public ActionResult Guest()
        {
            mytestContext db = new mytestContext();
            guests guest = db.guests.FirstOrDefault();
            
            return View();
            //return RedirectPermanent("/guests/chishi");
           
        }

假设你在Web.config的<system.web> 下有以下缓存配置文件:

<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name="HomePageProfile" duration="60"  VaryByParam="none">
</outputCacheProfiles>
</outputCacheSettings>
</caching>

就可以在Action 套用以下属性:

[OutputCache(CacheProfile = "HomePageProfile")]
        public ActionResult Guest()
        {
            mytestContext db = new mytestContext();
            guests guest = db.guests.FirstOrDefault();
            
            return View();
            //return RedirectPermanent("/guests/chishi");
           
        }

猜你喜欢

转载自my.oschina.net/u/2494395/blog/1559951