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)  
                                    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 { }  
                            break;  
                Task.WaitAll();  
                if (totalUsage > 0)  
                    Models.Usage.Add_Update(iccid, period, totalUsage, network);  
			 

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.

Make HTTP requests using IHttpClientFactory in ASP.NET Core

Hi @AgaveJoe

I'm in learning process, if you don't mind, can you give me a simple example for doing HTTP GET?

I have tried below:

program.cs

            builder.Services.AddHttpClient();  

class1.cs

            private readonly IHttpClientFactory _httpClientFactory;  
            public async Task<bool> test1  
            for (int pageNo = 1; pageNo <= 10; pageNo++)  
                var httpRequestMessage = new HttpRequestMessage(  
                HttpMethod.Get,  
                $"https://xxxx.xxx.com/test/?per_page=500&page={pageNo}")  
                    Headers = { { HeaderNames.Authorization, "Token " + token } }  
                var httpClient = _httpClientFactory.CreateClient();  
                var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage);  
                if (httpResponseMessage.IsSuccessStatusCode)  
                    using var contentStream =  
                        await httpResponseMessage.Content.ReadAsStreamAsync();  
											

I face the same error and I already followed the instruction in the official website but still get that error sometimes

May I know if I can find other solution ?

Definitely use IHttpClientFactory to create HttpClient - the wrong way of initialization.

It caused so much trouble for me.

Nice example here for Net MAUI

https://github.com/yogigrantz/MAUIWithHttpClientFactory/tree/main/MAUIMultiPage

builder.Services.AddHttpClient();