Output Caching, and in particular the OutputCacheAttribute, is one of those things that looks great on paper but usually fails miserably in practice unless you have the most simplest of caching needs. Still, if you can get away with it, decorating your ASP.NET MVC Actions with the OutputCacheAttribute would be considered a proven practice.
One of the obvious places you can take advantage of the Output Cache ActionFilterAttribute in the ASP.NET MVC Framework is on RSS Feeds like I do with the Tampa ASP.NET MVC Developer Group Website. For simple needs you can set VaryByParam=“none“ with some sort of realistic duration and be on your way:
[OutputCache(VaryByParam = "none", Duration = 300)]
public ActionResult Rss()
{
var feed = _syndicationService.FetchNewsFeed();
return new RssResult {Feed = feed};
}
Something like this is an ideal candidate for using the OutputCacheAttribute, because it just doesn't vary under any circumstances. At least not in my case.
Let me be the first to say that if you feel you will need to monkey with those settings, and you probably will, you should probably use cache profiles in web.config:
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<clear/>
<add
name="Rss"
duration="300"
varyByParam="none" />
</outputCacheProfiles>
</outputCacheSettings>
</caching>
and then just specify the profile in the OutputCacheAttribute:
[OutputCache(CacheProfile = "Rss")]
public ActionResult Rss()
{
var feed = _syndicationService.FetchNewsFeed();
return new RssResult {Feed = feed};
}
This will give you a little more flexibility if you find yourself being repetitive in your settings and want to stay DRY as well as just so you don't have to re-compile the application for such a silly need. Hardcoding stuff in your application is not a proven practice :)
Just be careful with this in not so trivial situations as you may end up with some undesirable behavior, like user-specific or role-specific pages being cached for unauthorized people to see and other things of that crazy nature. It is best that you don't prematurely optimize your website and get caught with an ugly caching bug. However, when used wisely, the OutputCacheAttribute can do some wonders in your ASP.NET MVC Web Applications.
David Hayden
ASP.MVC Tutorials