Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

c# - No cache with HttpClient in Windows Phone 8

I've read that in order to disable caching while using get and post methods in HttpClient, I need to use a WebRequestHandler as my HttpClient's HttpClientHandler, and change its cache policy. However, WebRequestHandler is not within System.Net.Http.dll, but rather in System.Net.Http.WebRequest.dll, so I tried to add the .dll to the project as a reference. I got an error message:

Microsoft Visual Studio

A reference to a higher version or incompatible assembly cannot be added to the project.

Again, after a little search, I concluded that the .dll file was blocked because it was downloaded from another source. To unblock it, I went on trying the solution here. However, it didn't work either and I'm still getting the same error when I try to add the .dll file as a reference.

All I want to do is disable caching using my HttpClient, am I doing anything wrong here? I'm open to any type of advice or help.

My system is Windows 8.1 and I'm using Visual Studio 2013. The project I'm working on is a Windows Phone 8 application. The directory of .dll I'm trying to reference is "C:WindowsMicrosoft.NETFrameworkv4.0.30319System.Net.Http.WebRequest.dll". Thank you in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's not possible to reference regular .NET assemblies in a Windows Phone 8 project. You can only use the .NET API for Windows Phone. This is a subset of regular .NET. See http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj207211%28v=vs.105%29.aspx for more info.

The default caching of HttpClient (and HttpWebRequest) can be worked around by appending a value to the query string. For example, a guid.

string uri = "http://host/path?cache=" + Guid.NewGuid().ToString();

A better solution, like pointed out in the comment above, is to set the "If-Modified-Since" header. HttpWebRequest has it built in:

HttpWebRequest request = HttpWebRequest.CreateHttp(url);
if (request.Headers == null)
    request.Headers = new WebHeaderCollection();
// Make sure that you format time string according RFC.
// Otherwise setting header value will give ArgumentException for culture like 'ti-ER'
request.Headers[HttpRequestHeader.IfModifiedSince] = DateTime.UtcNow.ToString("r"); 

But you could add the header manually using an HttpClient I guess.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...