System.Net.Http.HttpRequestException:将内容复制到流时出错。 ---> System.IO.IOException:响应提前结束

问题描述 投票:0回答:1

我正在使用以下代码来调用一些 http api

public static async Task<GenerricApiResponse> ProcessWebRequest<T>(string url, T req,ILog Logger, int timeoutInSeconds = 0)
    {
        var obj = new GenerricApiResponse();
        try
        {
            using (var client = new HttpClient())
            {
                var jsonRequest = JsonSerializer.Serialize(req);
                client.DefaultRequestHeaders.ExpectContinue = false;
                var content = new StringContent(jsonRequest);
                content.Headers.Clear();
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                if (timeoutInSeconds > 0)
                {
                    client.Timeout = new TimeSpan(0, 0, timeoutInSeconds);
                }
                var response = await client.PostAsync(url, content);                    
                obj.HttpResponseCode = response.StatusCode;

                try
                {
                    string responsecontent = null;
                    responsecontent = response.Content.ReadAsStringAsync().Result;
                    if (response.Content != null && response.Content.Headers != null)
                    {
                        obj.ResponseContentType = response.Content.Headers.ContentType.MediaType;
                        if (responsecontent != null && obj.ResponseContentType == "text/html")
                        {
                            if (responsecontent != null && responsecontent.Length > 1000)
                            {
                                responsecontent = responsecontent.Substring(0, 1000) + "...";
                            }
                        }
                    }

                    obj.Response = responsecontent;
                }
                catch
                {
                    obj.IsError = true;
                }
            }
        }
        catch (Exception ex)
        {               
            if (ex.InnerException is TimeoutException)
            {
                ex = ex.InnerException;
            }

            obj.IsError = true;
            obj.Exception = ex;
            obj.Response = ex.Message;                
        }
        return obj;
    }

但是出现错误

System.Net.Http.HttpRequestException:将内容复制到流时出错。 ---> System.IO.IOException:响应提前结束。

知道我的代码中缺少什么或者我做错了什么吗?

仍然明白。即使我已经过了 90 秒的超时时间,但没有效果。 奇怪的是有时它确实有效

c# httprequest httpclient .net-core-3.1
1个回答
0
投票

我也遇到这个异常。经过调查,默认情况下 HttpClient 等待响应标头+内容准备好所有方法,例如。 PostAsync、SendAsync、GetAsync。因此,如果响应没有/无效的内容长度。你会得到这个错误。请参阅这个。所以建议使用SendAsync(xxx, HttpCompletionOption.ResponseHeadersRead)

    using (var req = new HttpRequestMessage(HttpMethod.Post, url))
    {
        var body = File.ReadAllText("body.txt").Trim();

        req.Content = new StringContent(body, Encoding.UTF8, "application/json-patch+json");

        // the follow code throw exception
        // System.IO.IOException: The response ended prematurely
        // since 'HttpCompletionOption.ResponseContentRead' is the default behavior
        // var response = await httpClient.SendAsync(req, HttpCompletionOption.ResponseContentRead);

        var response = await httpClient.SendAsync(req, HttpCompletionOption.ResponseHeadersRead);

        response.EnsureSuccessStatusCode();
    }
© www.soinside.com 2019 - 2024. All rights reserved.