Web Caching - Sample Code in ASP.NET MVC

2017/6/303 min read
bookmark this
Responsive image

ASP.NET MVC's OutputCache

1. Permanently store cache on client and server

Following example code, permanently cache page on client and server means once browser loads the page the page will remain on the page forever unless server rebuild, since cache on the server another agent will use the same server cache version as well. This is good for static resource and the resource won't change until server rebuild.

[OutputCache(Duration =int.MaxValue)]
public ActionResult Index()
return View();

The code above will response as following, the key here is max-age (in seconds). As you can see it means the page will keep a cache for a year.

This Client Cache will not work if either user type,F5 or open developer console and check the.disable cache Otherwise, the browser will use the cached version from a client machine.

HTTP/1.1 304 Not Modified
Cache-Control: public, max-age=31535986
Expires: Sun, 01 Jul 2018 06:37:30 GMT
Last-Modified: Sat, 01 Jul 2017 06:37:30 GMT
Vary: *
Server: Microsoft-IIS/10.0
X-Powered-By: ASP.NET
Date: Sat, 01 Jul 2017 06:37:43 GMT

The client will store the cache on the machine, for example, Chrome will store the cached version at the following location.

{YourPCsLoginUser}\AppData\Local\Google\Chrome\User Data\Default\Cache

2. Permanently store cache on client

[OutputCache(Duration = int.MaxValue, Location = System.Web.UI.OutputCacheLocation.Client)]
public ActionResult About()
return View();

3. Use Cache profile

Instead of define cache at C#, you could add at Web.Config. The good to add to config is that you can modify the change without involving deployment.

            <add name="MyCacheProfile" duration="30" location="Client"/>

After defined at Web.Config, you can use the MVC action as follows. It is better to use at config if you use the common function and might change later.

        public ActionResult Test(int id)
            return View();

Reference Resources

Other Resources

  • YSlow
  • Pagespeed Insights
  • dotTrace - Make use of a profiler to discover memory leaks and performance problems in your application
  • Run as Release mode - not Debug mode, when in production, and also during performance profiling. Release mode is much faster. Debug mode can hide performance problems in your own code.
  • OutputCacheAttribute for cache not-prone-to-change content
  • Use ETags and expiration - write custom ActionResult

Best Practice or Tips

  1. Gzip would help the page performance
  2. Gzip would be done by IIS level, however, some people IIS level might be an issue.
  3. Gzip would reduce response size around 2MB to 50KB.