Click here to Skip to main content
6,629,885 members and growing! (23,287 online)
Email Password   helpLost your password?
Web Development » Caching » General     Intermediate License: The GNU General Public License (GPL)

ASP.NET MVC Result Cache

By Jorge Bay Gondra

Cache the ActionResult using an ActionFilter
C#.NET 3.5, ASP.NET, Architect, Dev
Version:7 (See All)
Posted:16 Feb 2009
Updated:17 Feb 2009
Views:8,570
Bookmarked:13 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
8 votes for this article.
Popularity: 3.24 Rating: 3.59 out of 5
1 vote, 12.5%
1

2
3 votes, 37.5%
3
1 vote, 12.5%
4
3 votes, 37.5%
5

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.

Using the Code

Add the ResultCache attribute to an action of a controller.

[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:

<%@ 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.

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.

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.

History

  • February 16, 2009 - Article submitted
  • February 17, 2009 - Code comments improved

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPL)

About the Author

Jorge Bay Gondra


Member
Jorge has been working with Microsoft technologies for more than 10 years. Born in Argentina, he lives in Spain since 2004.
He worked as a consultant for mayor companies including Log, HP and Avanade and holds some technical certifications including MCSD and MCAD.

Currently, He is developing the ASP.NET MVC open source project prsync.com.

Follow him on Twitter: twitter.com/jorgebg

Occupation: Software Developer
Location: Spain Spain

Other popular Caching articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 6 of 6 (Total in Forum: 6) (Refresh)FirstPrevNext
GeneralGood to know PinmemberDonsw9:32 5 Mar '09  
GeneralMy vote of 1 PinmemberAlKatawazi10:56 18 Feb '09  
GeneralRe: My vote of 1 PinmemberJorge Bay Gondra23:17 18 Feb '09  
GeneralGreat article... PinmemberJosemaproject6:26 16 Feb '09  
RantAlready been done by the Framework! PinmemberAlKatawazi10:55 18 Feb '09  
GeneralRe: Already been done by the Framework! PinmemberJorge Bay Gondra23:16 18 Feb '09  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 17 Feb 2009
Editor: Deeksha Shenoy
Copyright 2009 by Jorge Bay Gondra
Everything else Copyright © CodeProject, 1999-2009
Web20 | Advertise on the Code Project