Sunday, April 27, 2014

Dealing with ASP.NET MVC Device Output Caching Issues

ASP.NET MVC output caching supports variability by device. This is a useful feature to have when building a mobile version of the desktop site, for example. However; there has been a persistent bug in the output cache support. It was fixed for a short time, but it has mostly remained broken and still is even today (MVC 5.1). Instead of waiting for a fix, and having it break again like before, you can go around this issue.


Here is a relatively easy and transparent way to get around this bug:
  • Use VaryByCustom output cache parameter for the actions.
  • Use the cache profile support to implicitly inject your VaryByCustom parameter to your output cache.
  • Implement the custom parameter handling in your Global.asax.cs
Use VaryByCustom output cache parameter for the actions.

This is repetitive, so we want to avoid sprinkling this custom attribute everywhere. We can use the cache profile support in your Web.config to add this attribute implicitly. (Just set the timeouts in your config).

So, now your OutputCache annotation becomes:

Finally, we implement the custom cache handling in the Global.asax.cs:

Post a Comment