CODECUBE VENTURES

Avoid Caching of Ajax Requests

By on Programming

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 :-)

Latest post: Specialists vs Generalists

See more in the archives