System.Net.Http.HttpClient adding If-Modified-Sinc

2019-08-09 07:38发布

问题:

I am attempting to issue an Http Get request from a windows universal app and seeing an odd behavior. (not sure if the fact that it is a universal app is related or not).

The simplified code in question is this:

var client = new HttpClient();
var response = await client.GetAsync("https://storage.googleapis.com/pictureframe/settings.json");
var s = await response.Content.ReadAsStringAsync();

In a unit test or console app that works as expected and the variable s contains the json content.

However in the app where I am trying to add that code (Universal Windows App targeting Windows 10 build 10240) the raw http request looks like this:

GET https://storage.googleapis.com/pictureframe/settings.json HTTP/1.1
Host: storage.googleapis.com
If-Modified-Since: Sun, 27 Dec 2015 18:00:08 GMT
If-None-Match: "5c43f7f07270bda3b7273f1ea1d6eaf7"
Connection: Keep-Alive

The If-Modified-Since header rightly causes google to return 304 - not modified so I get no json file back. The thing is I am not adding that header, nor can I figure out where it is being added and how to stop it.

Is there a circumstance in which this would be expected and if so how does one control that behavior.

回答1:

This must be a side effect of System.Net.Http.HttpClient being on top of Windows.Web.Http.HttpClient on Windows 10 with .NET Core. Console apps still use the regular .NET Framework.

Since there is no way to control the cache using System.Net.Http.HttpClient/HttpClientHandler and System.Net.Http.WebRequestHandler is not available for UWP apps, then my recommendation is you switch to Windows.Web.Http.

Then try:

var filter = new HttpBaseProtocolFilter();

// Disable cache of responses.
filter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache;

// Pass filter to HttpClient constructor.
var client = new HttpClient(filter);

var response = await client.GetAsync(new Uri("http://example.com"));
var responseString = await response.Content.ReadAsStringAsync();

Make sure to uninstall and reinstall your app to clean the internet cache.