Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 有asp.net问题的ios推送通知?_C#_Asp.net_.net - Fatal编程技术网

C# 有asp.net问题的ios推送通知?

C# 有asp.net问题的ios推送通知?,c#,asp.net,.net,C#,Asp.net,.net,我正在使用.net服务器为iOS设备提供推送通知。在我的服务器端端口:2195和2196已打开。如果我在PHP端(同一服务器)使用iOS.p12/.pem文件-->它工作正常。但在.net方面,我无法发送通知 这是我的代码: [HttpGet] [ActionName("Checkpush")] public Object PushNotificationToApple(string deviceid) { // var push = new PushBroker(); //Wire up t

我正在使用.net服务器为iOS设备提供推送通知。在我的服务器端端口:2195和2196已打开。如果我在PHP端(同一服务器)使用iOS.p12/.pem文件-->它工作正常。但在.net方面,我无法发送通知

这是我的代码

[HttpGet]
[ActionName("Checkpush")]

public Object PushNotificationToApple(string deviceid)
{
// var push = new PushBroker();
//Wire up the events for all the services that the broker registers
//push.OnNotificationSent += NotificationSent;
//push.OnChannelException += ChannelException;
//push.OnServiceException += ServiceException;
//push.OnNotificationFailed += NotificationFailed;
//push.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
//push.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
//push.OnChannelCreated += ChannelCreated;
//push.OnChannelDestroyed += ChannelDestroyed;

//try
//{
// var appleCert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"~/apns-dev-cert.p12"));
// push.RegisterAppleService(new ApplePushChannelSettings(false, appleCert, "welcome123"));
// push.QueueNotification(new AppleNotification()
//  .ForDeviceToken("cd2887c4093569b3eed142320f21a81e521e486cf5c40467390901d3a191398b")//the recipient device id
// .WithAlert("Hello")//the message
// .WithBadge(1)
// .WithSound("default")
// );
//}
//catch (Exception ex)
//{
// throw ex;
//}
//push.StopAllServices(waitForQueuesToFinish: true);


Int64 result = 0;
////// Messages message = null;
//try
//{
// string strDeviceToken = "cd2887c4093569b3eed142320f21a81e521e486cf5c40467390901d3a191398b";
// string strPushMessage = "Good Morning!";
// var payload1 = new NotificationPayload(strDeviceToken, strPushMessage, 1, "default");
// payload1.AddCustom("RegionID", "IDQ10150");
// var p = new List<NotificationPayload> { payload1 };
// string certificatePath = System.Web.Hosting.HostingEnvironment.MapPath("~/apns-dev-cert.p12");

// var push = new PushNotification(true, certificatePath, "welcome123");
// // push.P12File = "D:/Projects/RKB_RestAPI/apns-dev-cert.p12";
// string strfilename = push.P12File;
// var message1 = push.SendToApple(p);
// foreach (var item in message1)
// {
// result = 1;
// }
//}
//catch (Exception ex)
//{
//}
// return result;
// int result=0;
int port = 2195;
String hostname = "gateway.push.apple.com";


//String certificatePath = new     X509Certificate2(System.IO.File.ReadAllBytes(p12File)
 // , p12FilePassword
// , X509KeyStorageFlags.MachineKeySet |
// X509KeyStorageFlags.PersistKeySet |
// X509KeyStorageFlags.Exportable);
X509Certificate2 clientCertificate = new     X509Certificate2(System.IO.File.ReadAllBytes(System.Web.Hosting.HostingEnvironme nt.MapPath("~/apns-dev-cert.p12"))
    , "welcome123"
  , X509KeyStorageFlags.MachineKeySet |
   X509KeyStorageFlags.PersistKeySet |
   X509KeyStorageFlags.Exportable);
  X509Certificate2Collection certificatesCollection = new    X509Certificate2Collection(clientCertificate);

  TcpClient client = new TcpClient(hostname, port);
  SslStream sslStream = new SslStream(client.GetStream(), false, new    RemoteCertificateValidationCallback(ValidateServerCertificate), null);

 try
  {
  sslStream.AuthenticateAsClient(hostname, certificatesCollection, SslProtocols.Ssl3, false);

  MemoryStream memoryStream = new MemoryStream();
  BinaryWriter writer = new BinaryWriter(memoryStream);
 writer.Write((byte)0); //The command
 writer.Write((byte)0); //The first byte of the deviceId length (big-endian first byte)
  writer.Write((byte)32); //The deviceId length (big-endian second byte)

  writer.Write(HexStringToByteArray(deviceid.ToUpper()));
  String payload = "{\"aps\":{\"alert\":\"" +"text messages" +"\",\"badge\":1,\"sound\":\"default\"}}";
  writer.Write((byte)0);
  writer.Write((byte)payload.Length);
  byte[] b1 = System.Text.Encoding.UTF8.GetBytes(payload);
  writer.Write(b1);
  writer.Flush();
  byte[] array = memoryStream.ToArray();
  sslStream.Write(array);
  sslStream.Flush();
  client.Close();
 //lblResponse.Text = "Sucess..";
 }
 catch (System.Security.Authentication.AuthenticationException ex)
 {
   client.Close();
    // lblResponse.Text = ex.Message;
      }
   catch (Exception e)
   {
   client.Close();
   // lblResponse.Text = e.Message;
   }
   return result;
  }
{"Message":"An error has occurred.","ExceptionMessage":"Transaction failed. The server response was: 5.7.1 Forged HELO .","ExceptionType":"System.Net.Mail.SmtpException","StackTrace":"   at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response)\r\n   at System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, MailAddress from, Boolean allowUnicode)\r\n   at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception)\r\n   at System.Net.Mail.SmtpClient.Send(MailMessage message)\r\n   at RKB.RestAPI.V1Controller.Forgot(String emailid) in d:\\Projects\\RKB_RestAPI\\V1.cs:line 391\r\n   at lambda_method(Closure , Object , Object[] )\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass13.<GetExecutor>b__c(Object instance, Object[] methodParameters)\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.<>c__DisplayClass5.<ExecuteAsync>b__4()\r\n   at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)"}
[HttpGet]
[ActionName(“Checkpush”)]
公共对象PushNotificationToApple(字符串设备ID)
{
//var push=new PushBroker();
//连接代理注册的所有服务的事件
//push.OnNotificationSent+=NotificationSent;
//push.OnChannelException+=ChannelException;
//push.OnServiceException+=ServiceException;
//push.OnNotificationFailed+=NotificationFailed;
//push.OnDeviceSubscriptionExpired+=设备SubscriptionExpired;
//push.OnDeviceSubscriptionChanged+=设备SubscriptionChanged;
//push.OnChannelCreated+=ChannelCreated;
//push.onchanneldestrocted+=channeldestrocted;
//试一试
//{
//var appleCert=File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,“~/apns-dev-cert.p12”);
//RegisterAppleService(新的ApplePushChannelSettings(false,appleCert,“welcome123”);
//push.QueueNotification(新应用程序化()
//.ForDeviceToken(“cd2887c4093569b3eed142320f21a81e521e486cf5c40467390901d3a191398b”)//接收方设备id
//.WithAlert(“你好”)//消息
//.带徽章(1)
//.使用声音(“默认”)
// );
//}
//捕获(例外情况除外)
//{
//掷骰子;
//}
//push.StopAllServices(waitForQueuesToFinish:true);
Int64结果=0;
//////Messages=null;
//试一试
//{
//字符串strDeviceToken=“cd2887c4093569b3eed142320f21a81e521e486cf5c40467390901d3a191398b”;
//string strPushMessage=“早上好!”;
//var payload1=新的通知有效载荷(strDeviceToken,strPushMessage,1,“默认值”);
//payload1.AddCustom(“RegionID”、“IDQ10150”);
//var p=新列表{payload1};
//string certificatePath=System.Web.Hosting.HostingEnvironment.MapPath(“~/apns-dev-cert.p12”);
//var push=新push通知(true,certificatePath,“welcome123”);
////push.P12File=“D:/Projects/RKB_RestAPI/apns-dev-cert.p12”;
//字符串strfilename=push.p12文件;
//var message1=push.SendToApple(p);
//foreach(消息1中的变量项)
// {
//结果=1;
// }
//}
//捕获(例外情况除外)
//{
//}
//返回结果;
//int结果=0;
int端口=2195;
字符串hostname=“gateway.push.apple.com”;
//String certificatePath=new X509Certificate2(System.IO.File.ReadAllBytes(p12文件)
//,p12文件密码
//,x509keystrageflags.MachineKeySet|
//X509keystrageFlags.PersistKeySet|
//X509keystrageFlags.可出口);
X509Certificate2 clientCertificate=新的X509Certificate2(System.IO.File.ReadAllBytes(System.Web.hostingEnvironment nt.MapPath(“~/apns-dev-cert.p12”))
“欢迎光临”
,x509keystrageflags.MachineKeySet|
X509keystrageFlags.PersistKeySet|
X509keystrageFlags.可出口);
X509Certificate2Collection certificatesCollection=新的X509Certificate2Collection(客户端证书);
TcpClient client=新的TcpClient(主机名、端口);
SslStream SslStream=新的SslStream(client.GetStream(),false,新的RemoteCertificateValidationCallback(ValidateServerCertificate),null);
尝试
{
sslStream.authenticatesClient(主机名、证书集合、SslProtocols.Ssl3、false);
MemoryStream MemoryStream=新的MemoryStream();
BinaryWriter=新的BinaryWriter(memoryStream);
writer.Write((字节)0);//命令
writer.Write((字节)0);//设备ID长度的第一个字节(big-endian第一个字节)
writer.Write((字节)32);//设备ID长度(大端第二字节)
Write(HexStringToByteArray(deviceid.ToUpper());
字符串有效载荷=“{\“aps\”:{\“警报\”:\“+”文本消息“+”,“徽章\”:1,\“声音\”:\“默认值\”}”;
writer.Write((字节)0);
writer.Write((字节)有效负载.Length);
byte[]b1=System.Text.Encoding.UTF8.GetBytes(有效负载);
writer.Write(b1);
writer.Flush();
字节[]数组=memoryStream.ToArray();
sslStream.Write(数组);
sslStream.Flush();
client.Close();
//lblResponse.Text=“成功…”;
}
捕获(System.Security.Authentication.AuthenticationException ex)
{
client.Close();
//lblResponse.Text=例如消息;
}
捕获(例外e)
{
client.Close();
//lblResponse.Text=e.消息;
}
返回结果;
}
我得到一个错误是

[HttpGet]
[ActionName("Checkpush")]

public Object PushNotificationToApple(string deviceid)
{
// var push = new PushBroker();
//Wire up the events for all the services that the broker registers
//push.OnNotificationSent += NotificationSent;
//push.OnChannelException += ChannelException;
//push.OnServiceException += ServiceException;
//push.OnNotificationFailed += NotificationFailed;
//push.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
//push.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
//push.OnChannelCreated += ChannelCreated;
//push.OnChannelDestroyed += ChannelDestroyed;

//try
//{
// var appleCert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"~/apns-dev-cert.p12"));
// push.RegisterAppleService(new ApplePushChannelSettings(false, appleCert, "welcome123"));
// push.QueueNotification(new AppleNotification()
//  .ForDeviceToken("cd2887c4093569b3eed142320f21a81e521e486cf5c40467390901d3a191398b")//the recipient device id
// .WithAlert("Hello")//the message
// .WithBadge(1)
// .WithSound("default")
// );
//}
//catch (Exception ex)
//{
// throw ex;
//}
//push.StopAllServices(waitForQueuesToFinish: true);


Int64 result = 0;
////// Messages message = null;
//try
//{
// string strDeviceToken = "cd2887c4093569b3eed142320f21a81e521e486cf5c40467390901d3a191398b";
// string strPushMessage = "Good Morning!";
// var payload1 = new NotificationPayload(strDeviceToken, strPushMessage, 1, "default");
// payload1.AddCustom("RegionID", "IDQ10150");
// var p = new List<NotificationPayload> { payload1 };
// string certificatePath = System.Web.Hosting.HostingEnvironment.MapPath("~/apns-dev-cert.p12");

// var push = new PushNotification(true, certificatePath, "welcome123");
// // push.P12File = "D:/Projects/RKB_RestAPI/apns-dev-cert.p12";
// string strfilename = push.P12File;
// var message1 = push.SendToApple(p);
// foreach (var item in message1)
// {
// result = 1;
// }
//}
//catch (Exception ex)
//{
//}
// return result;
// int result=0;
int port = 2195;
String hostname = "gateway.push.apple.com";


//String certificatePath = new     X509Certificate2(System.IO.File.ReadAllBytes(p12File)
 // , p12FilePassword
// , X509KeyStorageFlags.MachineKeySet |
// X509KeyStorageFlags.PersistKeySet |
// X509KeyStorageFlags.Exportable);
X509Certificate2 clientCertificate = new     X509Certificate2(System.IO.File.ReadAllBytes(System.Web.Hosting.HostingEnvironme nt.MapPath("~/apns-dev-cert.p12"))
    , "welcome123"
  , X509KeyStorageFlags.MachineKeySet |
   X509KeyStorageFlags.PersistKeySet |
   X509KeyStorageFlags.Exportable);
  X509Certificate2Collection certificatesCollection = new    X509Certificate2Collection(clientCertificate);

  TcpClient client = new TcpClient(hostname, port);
  SslStream sslStream = new SslStream(client.GetStream(), false, new    RemoteCertificateValidationCallback(ValidateServerCertificate), null);

 try
  {
  sslStream.AuthenticateAsClient(hostname, certificatesCollection, SslProtocols.Ssl3, false);

  MemoryStream memoryStream = new MemoryStream();
  BinaryWriter writer = new BinaryWriter(memoryStream);
 writer.Write((byte)0); //The command
 writer.Write((byte)0); //The first byte of the deviceId length (big-endian first byte)
  writer.Write((byte)32); //The deviceId length (big-endian second byte)

  writer.Write(HexStringToByteArray(deviceid.ToUpper()));
  String payload = "{\"aps\":{\"alert\":\"" +"text messages" +"\",\"badge\":1,\"sound\":\"default\"}}";
  writer.Write((byte)0);
  writer.Write((byte)payload.Length);
  byte[] b1 = System.Text.Encoding.UTF8.GetBytes(payload);
  writer.Write(b1);
  writer.Flush();
  byte[] array = memoryStream.ToArray();
  sslStream.Write(array);
  sslStream.Flush();
  client.Close();
 //lblResponse.Text = "Sucess..";
 }
 catch (System.Security.Authentication.AuthenticationException ex)
 {
   client.Close();
    // lblResponse.Text = ex.Message;
      }
   catch (Exception e)
   {
   client.Close();
   // lblResponse.Text = e.Message;
   }
   return result;
  }
{"Message":"An error has occurred.","ExceptionMessage":"Transaction failed. The server response was: 5.7.1 Forged HELO .","ExceptionType":"System.Net.Mail.SmtpException","StackTrace":"   at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response)\r\n   at System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, MailAddress from, Boolean allowUnicode)\r\n   at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception)\r\n   at System.Net.Mail.SmtpClient.Send(MailMessage message)\r\n   at RKB.RestAPI.V1Controller.Forgot(String emailid) in d:\\Projects\\RKB_RestAPI\\V1.cs:line 391\r\n   at lambda_method(Closure , Object , Object[] )\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass13.<GetExecutor>b__c(Object instance, Object[] methodParameters)\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.<>c__DisplayClass5.<ExecuteAsync>b__4()\r\n   at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)"}
{“Message”:“出现错误”,“ExceptionMessage”:“事务失败。服务器响应为:5.7.1伪造HELO”,“ExceptionType”:“System.Net.Mail.SmtpException”,“StackTrace”:“at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode,String response)\r\n at System.Net.Mail.MailCommand.Send(SmtpConnection conn,Byte[]命令,MailAddress from,Boolean AllowInocode)\r\n位于System.Net.Mail.SmtpTransport.SendMail(MailAddress发件人,MailAddressCollection收件人,字符串deliveryNotify,Boolean AllowInocode,SmtpFailedRecipientException&exception)\r\n位于System.Net.Mail.SmtpClient.Send(MailMessage message message)\r\n位于RKB.RestAPI.V1Controller.com(字符串emailid)在d:\\Projects\\RKB_RestAPI\\V1.cs:lambda_方法(闭包,对象,对象[])处的第391行\r\n\r\n在System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.c_u显示类13.b_uc(对象实例,对象[]方法参数)\r\n位于System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(对象实例,对象[]参数)\r\n位于System.Web.Http.Controllers.ReflectedHttpActionDescriptor.c_uDisplayClass5.b_u4()\r\n位于System.Threading.Tasks.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 Func,CancellationToken CancellationToken)})

我不知道我是从哪里犯的错误。你能帮我解决一下吗?

从你的例外情况来看,它是在试图发送电子邮件时出现的,因此它似乎与你上面发布的代码完全无关。我还推荐类似PushSharp的产品,它为各种通知提供了一个通用界面