ASP.NET MVC Result Cache

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.

Using the Code

Add the ResultCache attribute to an action of a controller.

Collapse
[ResultCache(Duration=60)]
public ActionResult About()
{
    //code that demands heavy CPU/DB time to execute 
    //...

    ViewData["DummyData"] = dummy;

    return View();
}

Here is the ViewPage code:

Collapse
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<h2>About</h2>
<p>
Sample ViewData value: <%=ViewData["DummyData"]%>
</p>
<p>
Sample Session dependant data <%=Session["UserName"] %>
</p>

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.

Collapse
public override void 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.

Collapse
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    string url = filterContext.HttpContext.Request.Url.PathAndQuery;
    this.CacheKey = "ResultCache-" + url;

    if (filterContext.HttpContext.Cache[this.CacheKey] != null)
    {
        //Setting the result prevents the action itself to be executed
        filterContext.Result = 
		(ActionResult)filterContext.HttpContext.Cache[this.CacheKey];
    }

    base.OnActionExecuting(filterContext);
}

About the Code

This cache approach is used in the open source MVC site prsync.com.
Get the full source code of the site at CodePlex.

 

About eagle081183

Passionate, Loyal
This entry was posted in ASP.NET MVC, C#. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s