Thursday, January 26, 2012

ASP.NET MVC OutputCache override


IE Strikes Again!

Because of my recent discovery of the IE9 “feature” that makes it cache unlike every other browser, I had to come up with a small change to our caching scheme on my project. To be fair, the IE9 team is actually well within RFC definitions of how to handle “cache-control: private”, so I shouldn’t complain too much about it. Though, why is it always IE that causes me to do extra coding?

Anyway, my solution was to add a “Default” OutputCache setting for all my MVC Controllers and then, to override these options on individual Controller Actions when needed.  The problem is: I can’t find any information on whether or not an OutputCache directive on an Action will override one on the Controller.

So, I wrote a quick test app to test it out. 

The Code

    // default everything to a tiny cache time
    [OutputCache(CacheProfile="ShortCache")]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";
            return View();
        }

        // change to a longer cache time
        [OutputCache(CacheProfile = "LongCache")]
        public ActionResult About()
        {
            return View();
        }
    }

Web.config mods

  
<system.web>
      <caching>
        <outputcachesettings>
          <outputcacheprofiles>
            <add duration="1" name="ShortCache" varybyparam="*">
            <add duration="60" name="LongCache" varybyparam="*">
          </add></add></outputcacheprofiles>
        </outputcachesettings>
      </caching>
  </system.web>

Results

Well, What do you know!? It worked! Hopefully someone else stumbles across this and saves themselves some time.

No comments:

Post a Comment