0

In my application, there is a functionality to extract reports based on a date range. In the background, it is calling my Web API with authentication(A), which consists of api caller functionality using httpclient, which is calling another non-secured DMZ server API (B) and a DMZ API-caliing WCF service (C) to collect data from the database. My problem is that whenever I select a large date range, I get the following error in my WebAPI (A).

System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: The underlying connection was closed: The connection was closed unexpectedly. at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult) at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar) --- End of inner exception stack trace --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at LRAS.OrderServices.Core.Helpers.ApiCaller.d__4.MoveNext()

What I have tried: I have increased the httpclient timeout from 300 to 1000 seconds, but it is breaking nearly every minute.

Amol Gomase
  • 19
  • 1
  • 2

1 Answers1

0

You can try several methods:
1.Configure the service point security protocol and select the SecurityProtocolType that suits you (Tls12, Ssl3, Tls, Tls11).

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

C# System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send
2.Set the ConnectionClose property of HttpClient.

_client.DefaultRequestHeaders.ConnectionClose = true;

HttpClient throwing "An error occurred while sending the request."

3.Try to hold the request long enough for it to complete normally and receive a valid response.

_client.DefaultRequestHeaders.Add("Connection", "Keep-Alive");
_client.DefaultRequestHeaders.Add("Keep-Alive", "3600");

.NET HttpClient - An existing connection was forcibly closed by the remote host

Lan Huang
  • 613
  • 2
  • 5
  • Thanks Lan Huang for your feedback. I tried all these solutions but nothing worked. – Amol Gomase Jan 19 '22 at 12:00
  • You can check the link I provided to find the solution.https://stackoverflow.com/questions/1459475/system-net-webexception-the-underlying-connection-was-closed-the-connection-wa/12764845 – Lan Huang Jan 20 '22 at 08:57