Antoine Trouve
Antoine Trouve

Reputation: 1273

The namespace System.Net.Cache does not exist

I am using the namespace System.Net.Http namespace with Xamarin in order to make calls to my HTTP REST API and it works fine. My http client code resides in the common portable project, and I call it from my android-only project (iOS is still in the backlogs)

Below is how it looks like:

Uri apiUri = new Uri("/example");
var request = (HttpWebRequest)HttpWebRequest.Create(apiUri);
request.ContentType = "application/json";
request.Method = "GET";
WebResponse response = await request.GetResponseAsync();

However, I suspect that consecutive GET to the same URL are cached. I have seen that it possible to remove the cache through HttpRequestCachePolicy objects, as described in https://developer.xamarin.com/api/type/System.Net.Cache.HttpRequestCachePolicy/ . My could should then look like:

Uri apiUri = new Uri("/example");
var request = (HttpWebRequest)HttpWebRequest.Create(apiUri);
request.ContentType = "application/json";
request.Method = "GET";
HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
request.CachePolicy = noCachePolicy;
WebResponse response = await request.GetResponseAsync();

However, the namespace System.Net.Cache is not defined anywhere and I cannot use this method. I am using the .NET SDK 4.5.

Is there some settings I am missing? Or should I look for a different way to disable GET request caching?

Below is the error I get:

The type or namespace name 'Cache' does not exist in the namespace 'System.Net' (are you missing an assembly reference?)

Upvotes: 0

Views: 509

Answers (1)

Antoine Trouve
Antoine Trouve

Reputation: 1273

Regardless what is the best way to hit an HTTP API (WebClient vs. HttpClient vs. HttpWebRequest), the comment from @ShushiHangover help we to figure out the point of my question.

The PCL output format used to be the norm for Xamarin "portable" projects. However, the namespace System.Net.Cache is not usable in PCL libraries. It is available in .NET Standard 2.0, which itself is not usable in PCL. PCL has been deprecated in summer 2017 in favor of .NET standard libraries, that allows to access to the .NET Standard 2.0 (among other benefits).

There is however no way to "convert" a project from PCL to .NET standard library but to make a new project and move all your files. Therefore I decided to create a new .NET standard library project that contains only my HTTP client code.

Upvotes: 1

Related Questions