0

I send HTTP request with the MultipartFormDataContent but I'm getting the following error when the file size is more than 2mb:

Error while copying content to a stream.
Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host..
An existing connection was forcibly closed by the remote host.

But exactly the same request with more than 5mb file can be sent with PostMan successfully.

This is my code:

using (var client = new HttpClient(GetHttpClientHandler(requestUrl)))
{
    using (var content = new MultipartFormDataContent())
    {
        for (int i = 0; i < images.Count; i++)
        {
            var fileName = $"file {(i + 1)}.png";
            ByteArrayContent bContent = new ByteArrayContent(images[i]);
            content.Add(bContent, "file", fileName);
        }

        using (var response = await client.PostAsync(requestUrl, content)) //Exception occurs here
        {
            resp = await response.Content.ReadAsStringAsync();
            response.EnsureSuccessStatusCode();
        }
        
    }
}

So, if the problem about the server-side why it works with PostMan? If the problem is in my code, what is that then? I think I did everything by convention.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Emba Ayyub
  • 657
  • 2
  • 7
  • 12

1 Answers1

0

This is not the recommended way of using HttpClient!

First create custom client servis with the required upload method:

public class MyClientService : IMyClientService
{
    private readonly HttpCLient _client;

    public MyClientService(HttpClient client)
    {
        _client = client;
    }


    public async Task<bool> UploadFilesAsync(MultipartFormDataContent content, string requestUrl)
    {
        var response = await _client.PostAsync(requestUrl, content);
        // ...
    }
}

Then register the custom client service in startup:

services.AddHttpClient<IMyClientService, MyClientService>();

Then inject your service to the controller/page model:

private readonly IMyClientService_client;

public UploadPage(IMyClientService client)
{
    _client = client;
}

And use it to upload files:

using (var content = new MultipartFormDataContent())
{
    for (int i = 0; i < images.Count; i++)
    {
        var fileName = $"file {(i + 1)}.png";
        ByteArrayContent bContent = new ByteArrayContent(images[i]);
        content.Add(bContent, "file", fileName);
    }

    var success = await _client.UploadFilesAsync(content, requestUrl);
}
LazZiya
  • 5,286
  • 2
  • 24
  • 37