C# 更改日期时的HttpClient缓存
我的应用程序与HttpClient存在问题。当我更改手机上的日期或时间时,HttpClient缓存会变得一团糟。例如,当我向后更改日期并再次运行应用程序时,每个响应都会从缓存中获取,而当我向前移动日期时,不会缓存任何请求,也不会从缓存中获取任何响应。我不知道问题出在哪里,所以如果遇到类似的问题,请帮助 有没有办法通过编程方式清除HttpClient缓存?我会在每次应用程序启动时都这么做 编辑: 我只是使用Fiddler查看响应,发现“Date”响应头中的时间是服务器上的正确时间,HttpClient可能将此头与设备上的时间一起用于计算,从而返回错误的结果 编辑2: 一个用例: 当用户打开应用程序并获取缓存控制头设置为10秒的url,然后关闭应用程序并前后更改时间,然后在某个时间再次打开应用程序时,在第一种情况下,httpclient始终从其缓存中获取相同url的响应,在第二种情况下,如果用户在10秒内多次请求同一个url,则不再使用缓存 我的代码是:C# 更改日期时的HttpClient缓存,c#,caching,windows-phone-8,windows-phone,dotnet-httpclient,C#,Caching,Windows Phone 8,Windows Phone,Dotnet Httpclient,我的应用程序与HttpClient存在问题。当我更改手机上的日期或时间时,HttpClient缓存会变得一团糟。例如,当我向后更改日期并再次运行应用程序时,每个响应都会从缓存中获取,而当我向前移动日期时,不会缓存任何请求,也不会从缓存中获取任何响应。我不知道问题出在哪里,所以如果遇到类似的问题,请帮助 有没有办法通过编程方式清除HttpClient缓存?我会在每次应用程序启动时都这么做 编辑: 我只是使用Fiddler查看响应,发现“Date”响应头中的时间是服务器上的正确时间,HttpClie
public async Task<StringServerResponse> DownloadJsonAsync(Uri uri, DecompressionMethods decompressionMethod = DecompressionMethods.None, int timeout = 30000, int retries = 3)
{
if (retries < 1 || retries > 10) retries = 3;
int currentRetries = 0;
// Baseline delay of 1 second
int baselineDelayMs = 1000;
// Used for exponential back-off
Random random = new Random();
StringServerResponse response = new StringServerResponse();
if (decompressionMethod == DecompressionMethods.GZip)
{
//Use decompression handler
using (var compressedHttpClientHandler = new HttpClientHandler())
{
if (compressedHttpClientHandler.SupportsAutomaticDecompression)
{
compressedHttpClientHandler.AutomaticDecompression = System.Net.DecompressionMethods.GZip;
}
using (var httpClient = new HttpClient(compressedHttpClientHandler))
{
httpClient.Timeout = TimeSpan.FromMilliseconds(timeout);
do
{
++currentRetries;
try
{
var httpResponse = await httpClient.GetAsync(uri, HttpCompletionOption.ResponseContentRead);
if (httpResponse.IsSuccessStatusCode)
{
response.StatusCode = httpResponse.StatusCode;
response.Content = await httpResponse.Content.ReadAsStringAsync();
return response;
}
}
catch (Exception)
{
}
int delayMs = baselineDelayMs + random.Next((int) (baselineDelayMs*0.5), baselineDelayMs);
if (currentRetries < retries)
{
await Task.Delay(delayMs);
DebugLoggingService.Log("Delayed web request " + delayMs + " seconds.");
}
// Increment base-delay time
baselineDelayMs *= 2;
} while (currentRetries < retries);
}
}
}
else
{
// same but without gzip handler
}
return null;
}
您可以尝试在URL中的输入查询中再添加一个参数。您可以阅读我的另一篇帖子:我不希望HttpClient停止使用其缓存,我只希望它能够正常工作,即使操作系统日期不正确,我认为缓存日期响应头可能是问题所在