System.Net.Http.HttpRequestException Error while copying content to a stream

后端 未结 3 2156
广开言路
广开言路 2020-12-14 17:10

I am using the HttpClient class in .NET Framework 4.5.2.

I calling PostAsync against a third party web service. 80% of the time this post works, 20%

3条回答
  •  生来不讨喜
    2020-12-14 18:02

    I had the same error (Error while copying content to a stream) with HTTPClient PutAsync() method:

    using (StreamContent content = new StreamContent(stream))
    {
        HttpResponseMessage response = await client.PutAsync(url, content))
    }
    

    You need to specify the HttpCompletionOption.ResponseHeadersRead flag which is not available in PutAsync so I switched to SendAsync:

    using (StreamContent content = new StreamContent(stream))
    {
        var httpRequest = new HttpRequestMessage(HttpMethod.Put, url);
        httpRequest.Content = content;
    
        HttpResponseMessage response = await client.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead);
    }
    

提交回复
热议问题