IOS Push Notification Sending Failed with SSL Connection Error

Sujit Kumar Ghosh 0 Reputation points
2023-05-14T07:29:04.1966667+00:00

IOS Push Notification Sending Failed. The SSL connection could not be established, see inner exception.


  Stack Trace:     at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean allowHttp2, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.GetHttp2ConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
   at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
   at servicewithtopself.Notification.SendIOSNotification(String deviceToken, String apnsId, Int32 notificationId, String title, String category, String message, String tags) in E:\Work\Source\App_ApplePushNotifyService\Main\App_ApplePushNotifyService\Notification.cs:line 218


I encountered an issue while trying to send an iOS push notification. The error message indicates that the SSL connection could not be established, with an inner exception.I also chceked my APNs certificate valid till september 2023. I am looking for guidance on how to resolve this error and establish a successful connection for push notifications. Any assistance or suggestions would be greatly appreciated.

**I attached my code sample.

        public void SendIOSNotification(string deviceToken, string apnsId, int notificationId, string title,string category, string message, string tags)
        {
            try
            {
                var url = string.Format("https://api.push.apple.com:443");
                string certificatePath = _config["Appsettings:CertificatePath"];
                string CertificatePassword = _config["Appsettings:CertificatePassword"];

                Utils.LogToFile(5, "[INFO]", "CertificatePath: " + certificatePath);
                var certData = System.IO.File.ReadAllBytes(certificatePath);
                var certificate = new X509Certificate2(certData, CertificatePassword, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

                var topic = "com.app.mobile";
                using (var httpHandler = new HttpClientHandler { SslProtocols = SslProtocols.Tls12 })
                {
                    var path = $"/3/device/{deviceToken}";

                    httpHandler.ClientCertificates.Add(certificate);
                    Utils.LogToFile(5, "[INFO]", "HTTP Handler Created");

                    using (var httpClient = new HttpClient(httpHandler, true))
                    {
                        Utils.LogToFile(5, "[INFO]", "HTTP Client Created");

                        using (var request = new HttpRequestMessage(HttpMethod.Post, new Uri(url + path)))
                        {
                            Utils.LogToFile(5, "[INFO]", "HTTP Request URI:" + (url + path));


                            request.Headers.TryAddWithoutValidation(":method", "POST");
                            request.Headers.TryAddWithoutValidation(":scheme", "https");
                            request.Headers.TryAddWithoutValidation(":path", path);
                            request.Headers.Host = "api.push.apple.com";

                            request.Headers.Add("apns-id", apnsId);
                            request.Headers.Add("apns-push-type", "alert");
                            request.Headers.Add("apns-topic", topic);
                            request.Headers.Add("apns-priority", "10");
                            request.Headers.Add("apns-expiration", "0");

                            var payload = new JObject {
                            {
                                "aps", new JObject
                                {
                                    { "alert", new JObject{
                                            { "title", title },
                                            { "body", message },
                                        }
                                    },
                                    { "sound", "default" },
                                    { "badge" , 1},
                                    { "content-available", 1 },
                                    { "category" , category}
                                }
                            },
                            { "alertmsg" , tags}
                        };

                            request.Content = new StringContent(payload.ToString());
                            request.Version = new Version(2, 0);

                            try
                            {
                                using (var httpResponseMessage = httpClient.SendAsync(request).GetAwaiter().GetResult())
                                {
                                    var responseContent = httpResponseMessage.Content.ReadAsStringAsync();

                                    int statusCode = (int)httpResponseMessage.StatusCode;
                                    string ReasonPhrase = httpResponseMessage.ReasonPhrase;
                                    string status = "", response = "";

                                    if (statusCode == 200)
                                    {
                                        Console.WriteLine("Notification successfully sent");
                                        Console.WriteLine($"status: {(int)httpResponseMessage.StatusCode} content: {responseContent.Result}");
                                        response = $"status: {(int)httpResponseMessage.StatusCode} content: {responseContent.Result}";
                                        status = "CO";
                                        Utils.LogToFile(1, "[SUCCESS]", "IOS Push Notification Sent. TokenId:" + deviceToken + ", Response:" + response);
                                    }
                                    else
                                    {
									
                                        Console.WriteLine("Notification sending failed");
                                        Console.WriteLine($"status: {(int)httpResponseMessage.StatusCode} content: {responseContent.Result}");
                                        response = $"status: {(int)httpResponseMessage.StatusCode} content: {responseContent.Result}";
                                        status = "E";
                                        Utils.LogToFile(1, "[FAILED]", "IOS Push Notification(API) Failed. TokenId:" + deviceToken + "\n" + ", Response: " + response);
                                    }
   
                                    UpdateDb(notificationId, status, response);
                                }
                            }
                            catch (Exception e)
                            {
                                Utils.LogToFile(1, "[FAILED]", "IOS Push Notification Sending Failed. " + e.Message + "  Stack Trace:  " + e.StackTrace);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Utils.LogToFile(1, "[EXCEPTION]", "IOS Push Notification Sending Failed. " + ex.Message + "  Stack Trace:  " + ex.StackTrace);
            }
            
        }
Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,001 questions
.NET
.NET
Microsoft Technologies based on the .NET software framework.
1,148 questions
.NET Runtime
.NET Runtime
.NET: Microsoft Technologies based on the .NET software framework.Runtime: The period of time during which a program is being executed in a computer.
996 questions
{count} votes