How to send a file and form data with HttpClient in C#

Here’s code I’m using to post form information and a csv file using (var httpClient = new HttpClient()) { var surveyBytes = ConvertToByteArray(surveyResponse); httpClient.DefaultRequestHeaders.Add(“X-API-TOKEN”, _apiToken); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(“application/json”)); var byteArrayContent = new ByteArrayContent(surveyBytes); byteArrayContent.Headers.ContentType = MediaTypeHeaderValue.Parse(“text/csv”); var response = await httpClient.PostAsync(_importUrl, new MultipartFormDataContent { {new StringContent(surveyId), “\”surveyId\””}, {byteArrayContent, “\”file\””, “\”feedback.csv\””} }); return response; } This is … Read more

Async call with await in HttpClient never returns

Check out this answer to my question which seems to be very similar. Something to try: call ConfigureAwait(false) on the Task returned by GetStreamAsync(). E.g. var result = await httpClient.GetStreamAsync(“weeklyplan”) .ConfigureAwait(continueOnCapturedContext:false); Whether or not this is useful depends on how your code above is being called – in my case calling the async method using … 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

Struggling trying to get cookie out of response with HttpClient in .net 4.5

To add cookies to a request, populate the cookie container before the request with CookieContainer.Add(uri, cookie). After the request is made the cookie container will automatically be populated with all the cookies from the response. You can then call GetCookies() to retreive them. CookieContainer cookies = new CookieContainer(); HttpClientHandler handler = new HttpClientHandler(); handler.CookieContainer = … Read more

How can I tell when HttpClient has timed out?

I am reproducing the same issue and it’s really annoying. I’ve found these useful: HttpClient – dealing with aggregate exceptions Bug in HttpClient.GetAsync should throw WebException, not TaskCanceledException Some code in case the links go nowhere: var c = new HttpClient(); c.Timeout = TimeSpan.FromMilliseconds(10); var cts = new CancellationTokenSource(); try { var x = await … Read more