System. Net .Http.HttpRequestException: Ошибка при копировании содержимого в поток. ---> System.IO.IOException: ответ закончился преждевременно - PullRequest
2 голосов
/ 14 февраля 2020

Я использую следующий код для вызова некоторых API-интерфейсов http

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 секунд как тайм-аут, но никакого эффекта. Странно, но когда-то это сработало

...