When or if to Dispose HttpResponseMessage when calling ReadAsStreamAsync?

So it seems like the calling code needs to know about and take ownership of the response message as well as the stream, or I leave the response message undisposed and let the finalizer deal with it. Neither option feels right. In this specific case, there are no finalizers. Neither HttpResponseMessage or HttpRequestMessage implement a … Read more

Trying to run multiple HTTP requests in parallel, but being limited by Windows (registry)

It is matter of ServicePoint. Which provides connection management for HTTP connections. The default maximum number of concurrent connections allowed by a ServicePoint object is 2. So if you need to increase it you can use ServicePointManager.DefaultConnectionLimit property. Just check the link in MSDN there you can see a sample. And set the value you … Read more

ASP.NET WebApi: how to perform a multipart post with file upload using WebApi HttpClient

After much trial and error, here’s code that actually works: using (var client = new HttpClient()) { using (var content = new MultipartFormDataContent()) { var values = new[] { new KeyValuePair<string, string>(“Foo”, “Bar”), new KeyValuePair<string, string>(“More”, “Less”), }; foreach (var keyValuePair in values) { content.Add(new StringContent(keyValuePair.Value), keyValuePair.Key); } var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(fileName)); fileContent.Headers.ContentDisposition = … Read more

Retrying HttpClient Unsuccessful Requests

Instead of implementing retry functionality that wraps the HttpClient, consider constructing the HttpClient with a HttpMessageHandler that performs the retry logic internally. For example: public class RetryHandler : DelegatingHandler { // Strongly consider limiting the number of retries – “retry forever” is // probably not the most user friendly way you could respond to “the … Read more

Should HttpClient instances created by HttpClientFactory be disposed?

Calling the Dispose method is not required but you can still call it if you need for some reasons. Proof: HttpClient and lifetime management Disposal of the client isn’t required. Disposal cancels outgoing requests and guarantees the given HttpClient instance can’t be used after calling Dispose. IHttpClientFactory tracks and disposes resources used by HttpClient instances. … Read more

PATCH Async requests with Windows.Web.Http.HttpClient class

I found how to do a “custom” PATCH request with the previous System.Net.Http.HttpClient class here, and then fiddled with until I made it work in the Windows.Web.Http.HttpClient class, like so: public async Task<HttpResponseMessage> PatchAsync(HttpClient client, Uri requestUri, IHttpContent iContent) { var method = new HttpMethod(“PATCH”); var request = new HttpRequestMessage(method, requestUri) { Content = iContent … Read more