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");
           
        }
相關文章
相關標籤/搜索