Why use HttpClient for Synchronous Connection

but what i am doing is purely synchronous You could use HttpClient for synchronous requests just fine: using (var client = new HttpClient()) { var response = client.GetAsync(“http://google.com”).Result; if (response.IsSuccessStatusCode) { var responseContent = response.Content; // by calling .Result you are synchronously reading the result string responseString = responseContent.ReadAsStringAsync().Result; Console.WriteLine(responseString); } } As far as … Read more

HttpClient – A task was cancelled?

There’s 2 likely reasons that a TaskCanceledException would be thrown: Something called Cancel() on the CancellationTokenSource associated with the cancellation token before the task completed. The request timed out, i.e. didn’t complete within the timespan you specified on HttpClient.Timeout. My guess is it was a timeout. (If it was an explicit cancellation, you probably would … Read more

HttpClient.GetAsync(…) never returns when using await/async

You are misusing the API. Here’s the situation: in ASP.NET, only one thread can handle a request at a time. You can do some parallel processing if necessary (borrowing additional threads from the thread pool), but only one thread would have the request context (the additional threads do not have the request context). This is … Read more

Do HttpClient and HttpClientHandler have to be disposed between requests?

The general consensus is that you do not (should not) need to dispose of HttpClient. Many people who are intimately involved in the way it works have stated this. See Darrel Miller’s blog post and a related SO post: HttpClient crawling results in memory leak for reference. I’d also strongly suggest that you read the … Read more

How do you set the Content-Type header for an HttpClient request?

The content type is a header of the content, not of the request, which is why this is failing. AddWithoutValidation as suggested by Robert Levy may work, but you can also set the content type when creating the request content itself (note that the code snippet adds application/json in two places-for Accept and Content-Type headers): … Read more