【问题标题】:Posting MultipartFormDataContent request with HttpClient gets Error while copying content to a stream使用 HttpClient 发布 MultipartFormDataContent 请求在将内容复制到流时出错
【发布时间】:2020-12-25 06:09:40
【问题描述】:

我使用 MultipartFormDataContent 发送 HTTP 请求,但当文件大小超过 2mb 时出现以下错误:

将内容复制到流时出错。
无法将数据写入传输连接:现有连接被远程主机强行关闭..
现有连接被远程主机强行关闭。

但是完全一样的超过 5mb 文件的请求可以用 PostMan 成功发送。

这是我的代码:

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();
        }
        
    }
}

那么,如果是关于服务器端的问题,为什么它与 PostMan 一起工作?如果问题出在我的代码中,那是什么?我想我做的一切都是按照惯例。

【问题讨论】:

    标签: asp.net-core httpclient


    【解决方案1】:

    这不是recommended way of using HttpClient

    首先使用所需的上传方法创建自定义客户端服务:

    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);
            // ...
        }
    }
    

    然后在启动时注册自定义客户端服务:

    services.AddHttpClient<IMyClientService, MyClientService>();
    

    然后将您的服务注入控制器/页面模型:

    private readonly IMyClientService_client;
    
    public UploadPage(IMyClientService client)
    {
        _client = client;
    }
    

    并用它来上传文件:

    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);
    }
    

    【讨论】:

    • 但是我需要在每个请求中向 HttpClientHandler 添加特定的凭据。按照您建议的方式,这是不可能的。
    • 我在帖子中添加了 GetHttpClientHandler 方法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    • 1970-01-01
    • 2018-08-14
    • 2016-01-18
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    相关资源
    最近更新 更多