Home c# HttpClient.PostAsync only works once
Reply: 1

c# HttpClient.PostAsync only works once

Vlorian
1#
Vlorian Published in 2018-01-12 14:52:40Z

I'm working on a windows client for uploading a lot of small files over an http post request. I’m using .NET 4.5.2

public async void Upload3(HttpClient client, string url, string[] files)
{
    foreach (var file in files)
    {
        using (var stream = new FileStream(file, FileMode.Open))
        {
            FileInfo info = new FileInfo(file);
            HttpContent fileStreamContent = new StreamContent(stream);
            using (var content = new MultipartFormDataContent())
            {
                content.Add(fileStreamContent);
                var response = await client.PostAsync(url, content);
                response.EnsureSuccessStatusCode();
                //code is stopping at the following line:
                string finalresults = await response.Content.ReadAsStringAsync();
                Console.WriteLine(finalresults);
                Console.WriteLine(" > Uploaded file " + info.Name);
            }
            stream.Close();
        }
    }
    Console.WriteLine("> Uploaded all files");
}

The Code is working fine for the very first file. But every other file is not uploaded. When I try to debug the code step by step, the code execution stops (in the second iteration of the loop) on this line:

string finalresults = await response.Content.ReadAsStringAsync();

Since the server log only shows on single request, I think that the error already occurs in this line:

var response = await client.PostAsync(url, content);

Even if I use different HttpClient objects and different FileStream objects, the upload is only working for the first file. What is wrong with this code?

Ishara Madawa
2#
Ishara Madawa Reply to 2018-01-12 16:12:03Z

For your requiment, you can user third party libraries like RESTSharp. There are lots of examples and good documentation. Also it is easy to use.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.322417 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO