coderox

How to bypass the local http caching mechanism

Tags: Windows Phone

When developing Windows Phone solutions, I've become quite fond of using the HttpWebRequest class to fetch information from the web, either if it's in XML or in JSON. I've also had the requirement to pull data down very often (as often as every 15 seconds) from the same URL and then stumbled into some issues. It seems like the Windows Phone platform is examining the URL you request and if you try to fetch data from the same URL as previous it will simply reply with a locally cached respones with the same data as earlier. This is probably not what you want and the solution is the following:

private HttpWebRequest CreateRequest(string url)
{
    var request = CreateRequest(url);
    if (request.Headers == null)
        request.Headers = new WebHeaderCollection();
    request.Headers[HttpRequestHeader.CacheControl] = "no-cache";
    request.Headers[HttpRequestHeader.IfModifiedSince] = DateTime.UtcNow.ToString();
    return request;
}

2 comments on “How to bypass the local http caching mechanism”

  1. Mike said

    The following line is irrelevant:

    request.Headers[HttpRequestHeader.CacheControl] = "no-cache"

    Since IfModifiedSince headers already make the request to be unique.
    So you can delete it.

    Also these lines are over explicit:
    if (request.Headers == null)
    request.Headers = new WebHeaderCollection();

    Setting Headers will create the collection if it is null.

  2. Cristian said

    If you want to be on the safe side it's good to include request.Headers[HttpRequestHeader.CacheControl] = "no-cache" because different webservers/proxyservers respond differently to cache requests and it can happen that they ignore the ifModifiedSince.

Add a Comment