HttpClient on .Net Standard 2.0

Hi there,

I’m working on a library for Unity where we can use the System.Net.Http.HttpClient in Unity targeting .Net Standard 2.0.
This works perfectly in a test project in Visual Studio, separate from Unity, but when used in Unity, the following code throws an exception:

        public static HttpClient Create(TimeSpan timeout = default(TimeSpan), ICredentials credentials = null, string proxy = null)
        {
            var useProxy = !string.IsNullOrEmpty(proxy);
            var config = new HttpClientHandler
            {
                UseProxy = useProxy,
                Proxy = useProxy ? new WebProxy(proxy) : null
            };
            if (useProxy)
                config.DefaultProxyCredentials = credentials;
            if (credentials != null)
            {
                config.UseDefaultCredentials = false;
                config.Credentials = credentials;
            }
            var client = new HttpClient(config);

            if (!timeout.Equals(default(TimeSpan)))
                client.Timeout = timeout;
            return client;
        }

The error thrown is InvalidOperationException:
Operation is not valid due to the current state of the object. at System.Net.Http.HttpClientHandler.set_Proxy (System.Net.IWebProxy value) [0x0000e] in <20a8f293e89843148f03a963627efba4>:0,
this references line 7 in the code above.

My question is: has anyone here encountered the same problem? Is the HttpClient class not fully supported when targeting .Net Standard 2.0? I’m at a loss here, the code compiles perfectly, but at runtime it seems it behaves quite differently in Unity vs. a normal .Net project.

It took me some time to get it right but httpClient is supported by Unity out of the box on .NET 2.0 standard targets. This is the code I ended up with to access a REST api:

public static async Task<Resource> GetResource()
        {
            using (var httpClient = new HttpClient())
            {
                httpClient.BaseAddress = new Uri(URL);
                httpClient.DefaultRequestHeaders.Accept.Clear();
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var response = await httpClient.GetAsync("api/session");
                if (response.StatusCode != HttpStatusCode.OK)
                    return null;
                var resourceJson = await response.Content.ReadAsStringAsync();
                return JsonUtility.FromJson<Resource>(resourceJson);
            }
        }
2 Likes