Avoid Caching of Ajax Requests
So we recently experienced a subtle little bug in an ajax enabled asp.net mvc application that only showed up in IE7. Turns out that the browser was caching an ajax request. To get around it, we made the following addition to the global.asax http application class:
public abstract class MyWebApplication : HttpApplication
{
protected MyWebApplication()
{
this.BeginRequest += new EventHandler(MyWebApplication_BeginRequest);
}void MyWebApplication_BeginRequest(object sender, EventArgs e)
{
string requestedWith = this.Request.Headers["x-requested-with"];
if (!string.IsNullOrEmpty(requestedWith) && requestedWith.Equals(“XMLHttpRequest”, StringComparison.InvariantCultureIgnoreCase))
{
this.Response.Expires = 0;
this.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
this.Response.AddHeader(“pragma”, “no-cache”);
this.Response.AddHeader(“cache-control”, “private”);
this.Response.CacheControl = “no-cache”;
}
}
}
Basically, any request that comes in with the x-requested-with header (which most or all ajax libs use) will get these extra headers added to the response to tell the browser to avoid caching.
Hope it helps someone else out there
Mike Said,
May 23, 2009 @ 3:39 pm
Hi, nice posts there
thank’s for the interesting information
Matt Said,
May 29, 2009 @ 8:04 am
Thanks – I pretty much came to the same conclusion on a recent app.
curious Said,
July 14, 2009 @ 10:03 am
And how exactly did this bug manifest itself?
Joel Martinez Said,
July 14, 2009 @ 10:51 am
I had an ajax application that was doing some polling to determine whether a long running server-side operation had completed. After long hours of troubleshooting a strange bug in IE7 where the request wouldn’t properly update to completed because of the caching.