You are not following the official HttpClient documentation. Register the HttpClient as a service and use dependency injection. You should have one HttpClient for each services and not dispose the HttpClient on each use. This can cause the connection issues described above.
System.IO.IOException: Unable to read data from the transport connection: Connection reset by peer
Dondon510
261
Reputation points
Hi,
I don't understand why some times I got the below exception?
System.AggregateException: One or more errors occurred. (The SSL connection could not be established, see inner exception.) ---> System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception. ---> System.IO.IOException: Unable to read data from the transport connection: Connection reset by peer
and I didn't find anything in my httpclient GET below:
double totalUsage = 0;
int pageNo = 0;
while (true)
{
pageNo++;
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.SslProtocols = System.Security.Authentication.SslProtocols.Tls13;
clientHandler.ServerCertificateCustomValidationCallback += (sender, cert, chain, sslPolicyErrors) => {
return true;
};
using (var client = new HttpClient(clientHandler))
{
var url = new Uri($"https://xx.xxxx.com/api/{iccid}/data/?startDate_from={period}&type=data&per_page=500&page=" + pageNo);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Token", token);
var response = await client.GetAsync(url);
HttpStatusCode statusCode = response.StatusCode;
if (statusCode == HttpStatusCode.OK)
{
response.EnsureSuccessStatusCode();
string res = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
try
{
JArray ja = JArray.Parse(res);
if (ja.HasValues)
{
if (string.IsNullOrEmpty(network))
{
network = (string)ja[0]["network"];
}
totalUsage = totalUsage + ja.Select(q => q["duration"].Value<double>()).Sum();
}
}
catch (Exception e) { await Helper.SaveLogAsync("Truphone.SIMs: " + e.ToString(), Errs.ErrType.Err); }
finally { }
}
}
else
break;
}
}
Task.WaitAll();
if (totalUsage > 0)
{
Models.Usage.Add_Update(iccid, period, totalUsage, network);
}