System.Net.Http.HttpClient添加If-Modified-Since标头 [英] System.Net.Http.HttpClient adding If-Modified-Since header
问题描述
我正在尝试从Windows通用应用程序发出Http Get请求,并发现异常行为. (不确定是通用应用程序的事实是否相关).
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();
在按预期工作的单元测试或控制台应用程序中,变量s
包含json内容.
In a unit test or console app that works as expected and the variable s
contains the json content.
但是,在我尝试添加该代码的应用程序中(针对Windows 10 build 10240的通用Windows应用程序),原始http请求看起来像这样:
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
If-Modified-Since
标头正确地导致Google返回304 - not modified
,所以我没有收到json文件.问题是我没有添加该标头,也无法弄清楚它的添加位置以及如何停止它.
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.
推荐答案
这必须是System.Net.Http.HttpClient
在 Windows 10 和 .NET上位于Windows.Web.Http.HttpClient
之上的副作用.核心.控制台应用程序仍使用常规的 .NET Framework .
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.
由于无法使用System.Net.Http.HttpClient/HttpClientHandler
控制缓存,并且System.Net.Http.WebRequestHandler
对于UWP应用程序不可用,因此我的建议是您切换到Windows.Web.Http
.
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
.
然后尝试:
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();
请确保卸载并重新安装您的应用程序以清理Internet缓存.
Make sure to uninstall and reinstall your app to clean the internet cache.
这篇关于System.Net.Http.HttpClient添加If-Modified-Since标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!