IE 9 AJAX request caching (MVC)

Standard

So IE9 is greedy when it comes to caching and automatically caches AJAX requests

This was an issue on an app that I’ve been working on that uses a lot of AJAX. IE9 was caching the AJAX requests and causing some problems downstream.

This can be stopped client side by setting cache to false in the JQuery ajaxSetup

$(document).ready(function() {
$.ajaxSetup({ cache: false });
});

However, I wanted to implement somthing server side, so that IE9 won’t cache any AJAX requests.

To do this I wrote an AjaxCacheControlAttribute that sniffs for AJAX requests and sets the relevant caching properites to prevent caching. To implement this across the app I then registered this in the GlobalFiltersCollection.

The attribute

public class AjaxCacheControlAttribute: ActionFilterAttribute
{
   public override void OnResultExecuted(ResultExecutedContext filterContext)
   {
       if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
       {
          filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
          filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
          filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
          filterContext.HttpContext.Response.Cache.SetNoStore();
       }
    }
}
About these ads

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s