【发布时间】:2019-01-22 17:00:59
【问题描述】:
我正在尝试从 C#/dotnetcore 发送推送通知,但在序列化并将我的有效负载发送到 APNS 时遇到了问题。
如果您查看下面的代码示例,iosPayload 对象有一个注释掉的属性。有效载荷中没有它,通知被成功接收,有它,通知不会到达设备。
错误为System.FormatException,消息为Additional non-parsable characters are at the end of the string。我实际上是从 Azure Webjob 中发送的,只有在那里我收到错误消息,使用简单的控制台应用程序在本地运行不会显示任何错误,但也永远不会到达设备。
public void SendNotification(string deviceToken)
{
int port = 2195;
string hostname = "gateway.sandbox.push.apple.com";
var iosPayload = new {
aps = new {
alert = "The title",
sound = "default"
},
app_group_id = 1,
notification_id = "notification_id",
campaignName = "Campaign Name",
push_title = "Campaign Title",
push_message = "The main body",
type = "sdkNotification",
push_on_click_behaviour = "1"//,
//another_property = "4"
};
string certificatePath = @"./com.myCompany.sampleIOS.DEV.p12";
X509Certificate2 clientCertificate = new X509Certificate2(File.ReadAllBytes(certificatePath), "");
X509Certificate2Collection certificatesCollection = new X509Certificate2Collection(clientCertificate);
TcpClient tcpClient = new TcpClient(hostname, port);
SslStream sslStream = new SslStream(tcpClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
try
{
sslStream.AuthenticateAsClient(hostname, certificatesCollection, SslProtocols.Tls, false);
MemoryStream memoryStream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(memoryStream);
writer.Write((byte)0);
writer.Write((byte)0);
writer.Write((byte)32);
writer.Write(HexStringToByteArray(deviceToken.ToUpper()));
var payload = JsonConvert.SerializeObject(iosPayload);
writer.Write((byte)0);
writer.Write((byte)payload.Length);
byte[] payloadBytes = System.Text.Encoding.UTF8.GetBytes(payload);
writer.Write(payloadBytes);
writer.Flush();
byte[] memoryStreamAsBytes = memoryStream.ToArray();
sslStream.Write(memoryStreamAsBytes);
sslStream.Flush();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
tcpClient.Close();
}
}
private byte[] HexStringToByteArray(string hexString)
{
return Enumerable.Range(0, hexString.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hexString.Substring(x, 2), 16))
.ToArray();
}
private bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None) return true;
return false;
}
编辑:奇怪的是我可以从 Pusher 发送我的完整有效负载...
【问题讨论】:
标签: c# .net .net-core apple-push-notifications