Sponsored

Thursday, July 3, 2014

Cheat Sheet for Enabling Output Caching in ASP.NET MVC

What is Output Caching


ASP.NET output caching feature allows increasing web application performance by returning content that was built some time ago instead of rebuilding it on every request. Returning content from cache only takes a few milliseconds as opposed to executing a full request cycle that could take much longer.
The content is being cached on the ASP.NET level and the request would not reach the application code for the content that is still in cache. ASP.NET output caching can be used in both WebForms and MVC applications and using it in MVC has become even easier than before.

When to use Output Caching


Output caching is useful when content returned by a controller action method does not change frequently, requires more than few CPU cycles or database access and does not require a lot of memory to store. For example, I would not recommend to use output caching for a large binary object like an image or a file. Also there is no point to cache a short string that only takes a few milliseconds to build. The best use case would be an average size content that requires some calculation or database access to produce but does not change on every request.

How to enable Output Caching


The easiest way to enable output caching in MVC is using an OutputCache attribute on the controller or controller action method. Applying output caching on a controller action method is recommended as it gives much better granularity and control over output caching. The best way to control output caching behaviour is via caching profiles that allow defining all parameters in a web.config file and override them for each environment where the web application is deployed (i.e. Dev, QA, Stage, Live, etc.)

Limitations


ASP.NET MVC has some limitations for output caching, for example: caching profile is not supported for a partial/child controller method therefore caching parameters including Duration and VaryByParam must be set in the code.

Implementation and code review check points

  1. Apply to individual action methods
  2. Use Caching profiles
  3. Partial/child action methods should not be cached for too long
  4. Disable output caching in Dev/QA/Stage environment.
  5. Do not forget to set Duration and VaryByParam values in web.config

Example

<system.web>
  <caching>
    <outputcachesettings>
      <outputcacheprofiles>
        <add name="cacheProfile" duration="60" varyByParam="*" />
      </outputCacheProfiles>
    </outputCacheSettings>
  </caching>
</system.web>

[OutputCache(CacheProfile = "cacheProfile")]
public ActionResult Test()
{
    ViewData["result"] = "This text was rendered at " + DateTime.Now;
    return View();
}

No comments:

Post a Comment