Conditional HTTP download (If-Modified-Since) #2: Windows Store Apps

Remember the problem of the missing If-Modified-Since HTTP header property on Windows Phone’s HttpWebRequest described in my last post? When trying to re-use some of the code I’ve suggested as solution to that problem in a Windows Store App, I noticed that the IfModifiedSince property is missing in the WinRT HttpWebRequest too, and that the suggested solution of setting the header field manually doesn’t work because (according to the exception I got) “the ‘If-Modified-Since’ header must be modified using the appropriate property or method”! The framework tries to be funny by suggesting to use a property that does not exist!? Now, how to solve this?

Well, basically Microsoft would like you to use HttpClient instead of HttpWebRequest. The advantage of this approach is that HttpClient offers the desired IfModifiedSince property (and, by the way, HttpClient fully supports asynchronous operations out of the box, which is a nice side-effect). To switch from HttpWebRequest, you could do something like the following:

using (HttpClient request = new HttpClient())
{
	request.DefaultRequestHeaders.IfModifiedSince = new DateTime(YOUR_DATE_VALUE); 
	HttpResponseMessage response = await request.GetAsync(YOUR_URL); 
	switch (response.StatusCode) 
	{ 
		case HttpStatusCode.NotModified: 
		// Online version does not differ from local version 
		case HttpStatusCode.OK: 
		// Online version has been updated - start the actual download 
	}
}

If you really want to stick with HttpWebRequest, as a workaround you could download the header and compare the Last-Modified date manually, if this header field is provided by the HTTP server. The trick is to use the HEAD method instead of GET, which does not download the requested content as a whole, but only the header:

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(YOUR_URL); 
req.Method = "HEAD"; 
using (WebResponse response = await req.GetResponseAsync()) 
{ 
	if (DateTime.Parse(response.Headers["Last-Modified"]) > new DateTime(YOUR_DATE_VALUE)) 
	{ 
		// Online version has been updated - start the actual download 
	} 
	else 
	{ 
		// Online version does not differ from local version 
	} 
}