MVC过滤器之结果过滤器

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

因为从Action回传的ActionResult必定有个ExecuteResult方法用来运行检视的结果,因此,经过这个过滤器能够在运行以前整理一些信息给ActionResult使用,或在运行以后对结果进行,最多见的例子就是实做输出缓存机制,Asp.net MVC 内建的属性有OutPutCache属性。缓存

来个实例:.net

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

[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 套用如下属性:it

[OutputCache(CacheProfile = "HomePageProfile")]
        public ActionResult Guest()
        {
            mytestContext db = new mytestContext();
            guests guest = db.guests.FirstOrDefault();
            
            return View();
            //return RedirectPermanent("/guests/chishi");
           
        }
相关文章
相关标签/搜索