We have implemented IHttpClientFactory
to make the third party calls using HttpClient
in .NET Core. However, we are still getting the below errors.
System.IO.IOException: Unable to read data from the transport connection: The I/O operation has been aborted because of either a thread exit or an application request.
System.Net.Sockets.SocketException (995): The I/O operation has been aborted because of either a thread exit or an application request
System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.IO.IOException: The response ended prematurely
This is the code in which we have configured the things:
Startup.cs
builder.Services
.AddHttpClient<IRequestHandler, RequestHandler>()
.SetHandlerLifetime(TimeSpan.FromMinutes(5))
.ConfigurePrimaryHttpMessageHandler(_ => new HttpClientHandler
{
SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13
})
.AddPolicyHandler(retryPolicyHttp);
services.AddTransient<IRequestHandler, RequestHandler>();
RequestHandler.cs
public class RequestHandler: IRequestHandler
{
private readonly IHttpClientFactory _httpClientFactory;
public RequestHandler(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
public virtual HttpResponseMessage ExecuteThirdPartyServices(HttpMethod httpMethod, string
postData, RequestModel requestModel)
{
using HttpRequestMessage request = new(httpMethod, requestModel.RequestUri);
HttpResponseMessage httpMessageResponse;
using (var httpClient = _httpClientFactory.CreateClient())
{
httpClient.Timeout = TimeSpan.FromMinutes(5);
httpMessageResponse = httpClient.SendAsync(request).Result;
}
return httpMessageResponse;
}
}
I have tried all sort of options to resolve these errors but still we are not able to pass these errors and we keep on getting these errors.
Any help on this is appreciated!