Introduction

The idea behind this cache approach is plain simple: the web application should cache ActionResults that demand heavy CPU/DB time to load. Currently, the ASP.NET MVC Framework has a cache feature, the OutputCache, that works by storing a copy of the resulting webpage. This feature does not fit a scenario where the webpage is dependant, for example, on session data.

The code in the ViewPage is not affected by using the ResultCache. In the sample, the View shows the data from the ViewData (can be cached) and the Session.

How It Works

After the Action executes, the Action Filter stores the ActionResult in the application Cache.

publicoverridevoid OnActionExecuted(ActionExecutedContext filterContext)
{
//Add the ActionResult to cache
filterContext.HttpContext.Cache.Add(this.CacheKey, filterContext.Result,
Dependency, DateTime.Now.AddSeconds(Duration),
System.Web.Caching.Cache.NoSlidingExpiration, Priority, null);
//Add a value in order to know the last time it was cached.
filterContext.Controller.ViewData["CachedStamp"] = DateTime.Now;
base.OnActionExecuted(filterContext);
}

The next time the Action is invoked, the attribute will retrieve the result from cache preventing the Action from executing.

This is exactly what I was looking for. I only wanted to cache the action result, not the entire view. Kind of odd that the built-in cache doesn't have the option to disable caching the view. It makes even a simple <%=DateTime.Now%> not function as needed. Excellent solution.

Hi AlKatawazi,As I said in the Intro of the article, the MVC Framework comes with the OutputCache action filter, but that works by storing a copy of the resulting webpage and if you use session or non-deterministic data the caching it won't work as expected.This action filter, on the other hand, caches the ActionResult (with the ViewDataCollection in it) and not the resulting webpage.Please read the article before you comment. Kind Regards,Jorge

Hi AlKatawazi,As I said in the Intro of the article, the MVC Framework comes with the OutputCache action filter, but that works by storing a copy of the resulting webpage and if you use session or non-deterministic data the caching it won't work as expected.This action filter, on the other hand, caches the ActionResult (with the ViewDataCollection in it) and not the resulting webpage.Please read the article before you comment.Kind Regards,Jorge