使用FCM将通知从Web数据推送到Mobile App

时间:2019-01-28 06:06:55

标签: c# firebase asp.net-mvc-4 xamarin.android firebase-cloud-messaging

所以我已经设置了项目,甚至尝试通过从Cloud Messaging添加示例通知来测试它,并在我的Android仿真器中接收该通知。

enter image description here

但是,当网络发生变化时,我需要将其推送到移动设备。 所以我在网上尝试了这段代码:

public void PushNotificationToFCM()
        {
            try
            {
                var applicationID = "AIzaSyDaWwl..........";
                var senderId = "487....";
                string deviceId = "1:487565223284:android:a3f0953e5fbdd790";
                WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
                tRequest.Method = "post";
                tRequest.ContentType = "application/json";
                var data = new
                {
                    to = deviceId,
                    notification = new
                    {
                        body = "sending to..",
                        title = "title-----"
                    }
                };
                var serializer = new JavaScriptSerializer();
                var json = serializer.Serialize(data);
                Byte[] byteArray = Encoding.UTF8.GetBytes(json);
                tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));
                tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
                tRequest.ContentLength = byteArray.Length;
                using (Stream dataStream = tRequest.GetRequestStream())
                {
                    dataStream.Write(byteArray, 0, byteArray.Length);
                    using (WebResponse tResponse = tRequest.GetResponse())
                    {
                        using (Stream dataStreamResponse = tResponse.GetResponseStream())
                        {
                            using (StreamReader tReader = new StreamReader(dataStreamResponse))
                            {
                                String sResponseFromServer = tReader.ReadToEnd();
                                string str = sResponseFromServer;
                            }
                        }
                    }
                }
            }

            catch (Exception ex)
            {
                string str = ex.Message;
            }
        }

响应为:

{"multicast_id":7985385082196953522,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}

请帮助我。谢谢。

1 个答案:

答案 0 :(得分:1)

我建议您检查一下Nico Bonoro撰写的这份惊人的指南,该指南解释了您逐步configure firebase with a .Net backend要做的一切

使用以下方法创建名为PushNotificationLogic.cs的静态类:

添加一个名为SendPushNotifications的静态方法,其中这些参数为:

  • deviceTokens:字符串数组,每个字符串代表Firebase在每次安装应用时提供的FCM令牌。这将是通知将要发送的应用安装列表。
  • 标题:这是通知的粗体部分。
  • 正文:代表Firebase SDK的“消息文本”字段,这是您要发送给用户的消息。
  • 数据:有一个动态对象,它可以是您想要的任何对象,因为该对象将用作要发送给应用程序的其他信息,就像隐藏的信息一样。例如,当用户按下某些产品的通知或ID时要执行的操作。

对于该方法,我将假设所有参数正确且没有错误值(您可以添加所需的所有验证)。我们要做的第一件事就是创建一个包含所有需要发送到API的数据的对象

添加以下两个类:

public class Message
{
  public string[] registration_ids { get; set; }
  public Notification notification { get; set; }
  public object data { get; set; }
}
  public class Notification
{
   public string title { get; set; }
   public string text { get; set; }
}

然后,只需创建一个类型为“消息”的新对象,并按照我在此处进行的操作对其进行序列化:

var messageInformation = new Message()
{
   notification = new Notification()
  {
    title = title,
    text = body
  },
  data = data,
  registration_ids = deviceTokens
 };
 //Object to JSON STRUCTURE => using Newtonsoft.Json;
 string jsonMessage = JsonConvert.SerializeObject(messageInformation);

注意:您将需要在项目中添加NewtonSoft.Json

现在,我们只需要对Firebase API的请求就可以了。该请求必须作为Firebase API网址的“发布”方法,我们必须添加一个标头,即“ Authorization”(授权),并使用“ key = {Your_Server_Key}”之类的值。然后我们添加内容(jsonMessage),您就可以使用API​​。

// Create request to Firebase API
var request = new HttpRequestMessage(HttpMethod.Post, FireBasePushNotificationsURL);
request.Headers.TryAddWithoutValidation(“Authorization”, “key=” + ServerKey);
request.Content = new StringContent(jsonMessage, Encoding.UTF8, “application/json”);
HttpResponseMessage result;
using (var client = new HttpClient())
{
   result = await client.SendAsync(request);
}

如有查询,祝您好运。