.NET Core 2.1 Apple Push-уведомления - PullRequest
0 голосов
/ 19 ноября 2018

Мне нужно отправлять push-уведомления на определенные устройства iOS с моим .Net Core WebAPI, который будет выполняться на Windows 2008 Server R2.Сам сервер не должен быть проблемой, потому что он работает с библиотекой node.js.Но я хочу, чтобы он работал с WepAPI в ASP .Net Core 2.1, который размещается на встроенном сервере Kestrel.Может быть, у вас есть идея, как решить эту проблему.

Мой код:

// 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: полученное сообщение было неожиданным или неправильно отформатированным --- Конец трассировки стека внутренней исключительной ситуации ---

1 Ответ

0 голосов
/ 22 ноября 2018

вы можете попробовать добавить информацию о версии к вашему запросу после строки apns-topic , как показано ниже?Он завершился, и после добавления следующей строки я впервые получил ошибку «Bad Device Token».

request.Version = new Version(2, 0);
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

Я видел команду установки версии в посте ниже.

Как реализовать push-уведомления на основе маркеров Apple (с использованием файла p8) в C #?

...