我正在尝试从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发送我的全部有效载荷...
答案 0 :(得分:0)
原来,我正在调用Legacy Binary Provider API,该序列的第一个字节确定了命令。我通过命令0进行发送,该API的最大有效负载大小为256个字节。显然我的有效载荷比那大一点,并且被拒绝了。
然后我发送2作为命令并建立必要的帧数据。