Make your ASP.Net web app fly: caching Ajax responses
by Stuartpublished onI didn't realise until recently that it's possible to cache Ajax responses in a browser's cache. This is extemely helpful if you regularly load large static lists into pages. It's also pretty easy to implement (in ASP.Net WebAPI)
Step 1
To tell JQuery that you'd like to cache responses, you must add cache:true to your Ajax request:
$.ajax({
type: "GET",
url: "api/v1.0/countries",
},
cache: true,
If you set cache:false the JQuery framework appends _null={guid} to your querystring, rendering it unique and not suitable for caching. See here for more information.
Step 2
Modify your response headers for the controller methods you'd like to cache in your browser.
I found that setting the Expires and Public headers worked best for me:
response.Headers.CacheControl = new CacheControlHeaderValue() { Public = true, Expires = DateTime.Today.AddDays(1);
The Public setting tells the browser that it can accept caches from intermediary devices like proxy servers.
I found this page and this page useful.
Helpful hints
- Rather than modify all of the controller methods that I wanted to be cacheable, I created an Action Filter Attribute: [Cache(maxAgeMins=30)]. Click here for example.
- At the time of writing, Chrome doesn't cache items in the browser when the site is on HTTPS and using a self-signed certificate. This took an age to work out! See here for more details.
Comments