Intermittent Connection Timeout issue

Dey, Subir 0 Reputation points
2024-07-05T19:00:16.17+00:00

We have built a .Net Core 8.0 based project in which we are calling an external api every 5 mnts.

Everytime this code is invoked , it will fetch around 50 records and create the payload in json object and do a PostAsync call to th external url. I am facing a problem while trying to do client.PostAsync() call to a external api. SOmetimes it goes through successfully , but more of the times , it fails and I have to retry to get the post call successful.

The same code used to work earlier when it was working in older .Net framework.

Code=======================

HttpClient client = new HttpClient();

client.DefaultRequestHeaders.Accept.Clear();

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

var credentials = Encoding.ASCII.GetBytes(usr + ":" + password);

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(credentials));

try

{

client.BaseAddress = new Uri(api_url);

var stringContent = new StringContent(strpayload, Encoding.UTF8, "application/json");

HttpResponseMessage responseMessage = client.PostAsync(api_url, stringContent).Result;

var responseFromAPI = responseMessage.Content.ReadAsStringAsync().Result;

}

Error Details===================

Message Transmission Error : One or more errors occurred. (A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. (xxx.yyy.com:443)): at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)

at System.Threading.Tasks.Task`1.get_Result()

at SandBox.Hangfire.UI.Core.EventLogDomainService.Process(EventLog eventLog, String usr, String password, String to_mailids, String notification_flag, String environment, List`1 eventlogproperties, Int32 retrycount) in D:\a\1\s\Core\ExxxService.cs:line 286:System.Net.Http.HttpRequestException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. (xxx.yyy.com:443) ---> System.Net.Sockets.SocketException (10060): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource.GetResult(Int16 token)

at System.Net.Sockets.Socket.<ConnectAsync>g__WaitForConnectWithCancellation|285_0(AwaitableSocketAsyncEventArgs saea, ValueTask connectTask, CancellationToken cancellationToken)

at System.Net.Http.HttpConnectionPool.ConnectToTcpHostAsync(String host, Int32 port, HttpRequestMessage initialRequest, Boolean async, CancellationToken cancellationToken)

--- End of inner exception stack trace ---

at System.Net.Http.HttpConnectionPool.ConnectToTcpHostAsync(String host, Int32 port, HttpRequestMessage initialRequest, Boolean async, CancellationToken cancellationToken)

at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)

at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)

at System.Net.Http.HttpConnectionPool.AddHttp11ConnectionAsync(QueueItem queueItem)

at System.Threading.Tasks.TaskCompletionSourceWithCancellation`1.WaitWithCancellationAsync(CancellationToken cancellationToken)

at System.Net.Http.HttpConnectionPool.SendWithVersionDetectionAndRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken)

at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)

at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)

I want to understand what is causing this issue as same code was working seamlessly in older .net versions.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,011 questions
Azure App Service
Azure App Service
Azure App Service is a service used to create and deploy scalable, mission-critical web apps.
7,911 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Johan Smarius 470 Reputation points MVP
    2024-09-20T14:28:18.05+00:00

    You could try to increase the timeout limit for the connection. https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.timeout?view=net-8.0&wt.mc_id=MVP_310061. The error does indicate a connection problem and if you can get a connection from time to time, a time out limit increase could help.

    In your code, I do see the use of Result twice. Is there a way to make the method you use async so that you can await the calls?

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.