Wednesday, October 8, 2008

Ajax calls, Internet Explorer, and Caching

Tip of the day: Internet explorer caches HTTP GET requests when called through AJAX.

Now, why does this apply to you?

The reason this is important is in situations where you rapidly call an HTTP GET method from javascript. If you make the calls too rapidly in succession, you'll get the same information from each call, regardless of the .NET implementation of your web service. In fact, if you call them too quickly in succession, IE doesn't even make the call to the web service, but instead returns the cached data.

Let's say you have a web method called "GetNewRandom()". (This is definately an ironic name, given that calls to the Random class repeats the same values when called in rapid-fire succession.) Now, let's say you've decorated your GetNewRandom class like this:


[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]

public Int32 GetNewRandom()


    Byte[] bytes = new Byte[4];

    new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(bytes);

    return BitConverter.ToInt32(bytes, 0);


Now, let's say you need to call this repeatedly over and over again quickly. Apparently, since the header for this call is identical each time you call it, Internet Explorer will actually cache the value on the client, assuming that the data that will be returned will be the same as it was the time before, and you'll get the same value repeated, until IE deems the cached data worthy of deletion and refreshing. This can be extremely problematic.

The solution?

Set UseHttpGet to "false" if you absolutely, positively need new data every single time. IE doesn't cache the HTTP POST.