Cache By Browser using ASP.NET MVC
25 Feb 2010

asp.net c# caching css html iphone mvc


In an attempt to make my website iPhone compatible I have resorted to adding an "iPhone" specific style sheet to my web pages. By parsing the ASP.NET page's Request.UserAgent property for the words "iPhone" or "iPod" I detect whether my visitor is using Apple's mobile Safari browser. This allows me to add a mobile Safari specific style sheet to my web pages, which takes care of any CSS nasties such as text size adjusting etc. etc.

However I encountered a problem when trying to cache my ASP.NET MVC view output, as the version being displayed when using mobile Safari was often a cached version without the additional "iPhone" specific style sheet. In order to avoid this I needed to cache several versions of my web pages: one for regular browsers and one for "iPhone" users.

The answer was to create my own VaryByCustom attribute for ASP.NET CacheOuput. By adding the following code to my site's Global.asax I was able to cache my MVC view content using the same criteria that determined whether or not to show my "iPhone" specific style sheet.

Once I had overridden the GetVaryByCustomString method I could start to use it by setting the VarByCustom attribute when using Output Caching in my MVC controllers.

You can learn more about Output Caching at OutputCache - more examples - ASP.NET Tutorial.