.NET Core 2.1 Apple 推送通知 [英] .NET Core 2.1 Apple Push Notifications

查看:38
本文介绍了.NET Core 2.1 Apple 推送通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须使用将在 Windows 2008 Server R2 上执行的 .Net Core WebAPI 向特定的 iOS 设备发送推送通知.服务器本身应该不是问题,因为它正在使用 node.js 库.但我希望它与 ASP .Net Core 2.1 中的 WepAPI 一起使用,该 WebAPI 使用内置的 Kestrel 服务器自托管.也许你已经知道如何解决这个问题了.

I have to send push notifications to specific iOS devices with my .Net Core WebAPI that will be executed on a Windows 2008 Server R2. The server itself should not be the problem because it is working with a node.js library. But I want it to work with an WepAPI in ASP .Net Core 2.1 which is self hosted with the inbuilt Kestrel Server. Maybe you've got an idea how to solve this problem.

我的代码:

// This will encode the jason web token apns needs for the authorization
// get the base64 private key of the .p8 file from apple
string p8File = System.IO.File.ReadAllText(Settings.Apn.PrivateKey);
p8File = p8File.Replace("-----BEGIN PRIVATE KEY-----", string.Empty);
p8File = p8File.Replace("-----END PRIVATE KEY-----", string.Empty);
p8File = p8File.Replace(" ", string.Empty);

byte[] keyData = Convert.FromBase64String(p8File);
ECDsa key = new ECDsaCng(CngKey.Import(keyData, CngKeyBlobFormat.Pkcs8PrivateBlob));

ECDsaSecurityKey securityKey = new ECDsaSecurityKey(key) { KeyId = Settings.Apn.KeyId };
SigningCredentials credentials = new SigningCredentials(securityKey, "ES256");

SecurityTokenDescriptor descriptor =
    new SecurityTokenDescriptor
        {
            IssuedAt = DateTime.Now,
            Issuer = Settings.Apn.TeamId,
            SigningCredentials = credentials
        };

JwtSecurityTokenHandler jwtHandler = new JwtSecurityTokenHandler();
string encodedToken = jwtHandler.CreateEncodedJwt(descriptor);
this.log?.LogInformation($"Created JWT: {encodedToken}");

// The hostname is: https://api.development.push.apple.com:443
HttpClient client = new HttpClient { BaseAddress = new Uri(Settings.Apn.Hostname) };
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
this.log?.LogInformation("Initialized new HttpClient.");

// payload content for the apns
JObject payloadData = new JObject
                          {
                              new JProperty("alert", data.Message),
                              new JProperty("badge", 2),
                              new JProperty("sound", "default")
                          };
JObject payload = new JObject
                       {
                           new JProperty("aps", payloadData)
                       };
this.log?.LogInformation($"Setup payload: {payload}");

// HttpRequestMessage that should be send
HttpRequestMessage request = new HttpRequestMessage(
                                 HttpMethod.Post,
                                 $"{Settings.Apn.Hostname}/3/device/{data.DeviceId}")
                                 {
                                     Content = new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json")
                                 };
this.log?.LogInformation("Setup HttpRequestMessage.");

// Setup the header
request.Headers.Add("Authorization", $"Bearer {encodedToken}");
request.Headers.Add("apns-id", Guid.NewGuid().ToString());
request.Headers.Add("apns-expiration", DateTime.Now.AddDays(1).ToString(CultureInfo.InvariantCulture));
request.Headers.Add("apns-priority", "10");
request.Headers.Add("apns-topic", "de.gefasoft-engineering.FabChat");

// Debug logging
this.log.LogDebug(request.ToString());
this.log.LogDebug(await request.Content.ReadAsStringAsync());
this.log.LogDebug(request.RequestUri.Host + request.RequestUri.Port);

// Send request
var result = await client.SendAsync(request);
this.log?.LogInformation("Sent request.");
this.log?.LogInformation(await result.Content.ReadAsStringAsync());

我总是抛出以下异常:

System.Net.Http.HttpRequestException:无法建立 SSL 连接成立,见内部异常.--->System.Security.Authentication.AuthenticationException:身份验证失败,请参阅内部异常.--->System.ComponentModel.Win32Exception:收到的消息是意外或格式错误 --- 内部异常堆栈结束跟踪---

System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception. ---> System.Security.Authentication.AuthenticationException: Authentication failed, see inner exception. ---> System.ComponentModel.Win32Exception: The message received was unexpected or badly formatted --- End of inner exception stack trace ---

推荐答案

使用 CorePush 库

它非常轻巧.我在所有项目中使用它来发送 Firebase Android 和 Apple iOS 推送通知.有用的链接:

Use CorePush lib

It's very lightweight. I use it across all my projects to send Firebase Android and Apple iOS push notifications. Useful links:

  1. NuGet 包
  2. 文档

界面非常简单和简约:

发送 APN 消息:

var apn = new ApnSender(settings, httpClient);
await apn.SendAsync(notification, deviceToken);

如果需要,它还可以发送 Android FCM 消息:

var fcm = new FcmSender(settings, httpClient);
await fcm.SendAsync(deviceToken, notification);

这篇关于.NET Core 2.1 Apple 推送通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆