Asp.Net 的 FCM(Firebase 云消息传递)推送通知

FCM (Firebase Cloud Messaging) Push Notification with Asp.Net

我已经通过以下方法使用 asp .netGCM 消息推送到 google 服务器,

GCM Push Notification with Asp.Net

现在我已经计划升级到 FCM 方法,任何人对此有想法或在 asp .net 中开发它让我知道..

我认为您发送推送通知的方式没有任何变化。同样在 FCM 中,您将以与 GCM 相同的方式发出 HTTP POST 请求:

https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

{ "data": {
    "score": "5x1",
    "time": "15:10"
  },
  "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
}

阅读有关 FCM Server 的更多信息。

我现在能看到的唯一变化是目标 Url。期间.

C# 服务器端代码 Firebase 云消息

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;

namespace Sch_WCFApplication
{
    public class PushNotification
    {
        public PushNotification(Plobj obj)
        {
            try
            {    
                var applicationID = "AIza---------4GcVJj4dI";

                var senderId = "57-------55";

                string deviceId = "euxqdp------ioIdL87abVL";

                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 = obj.Message,

                        title = obj.TagMsg,

                        icon = "myicon"

                    }    
                };       

                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;

            }          

        }   

    }
}

APIKey 和 senderId ,你得到的就在这里--------如下(下图) (转到您的 firebase 应用程序)

这是我的 VbScript 示例,适合 vb:

//Create Json body
posturl="https://fcm.googleapis.com/fcm/send"
body=body & "{ ""notification"": {"
body=body & """title"": ""Your Title"","
body=body & """text"": ""Your Text"","
body=body & "},"
body=body & """to"" : ""target Token""}"

//Set Headers :Content Type and server key
set xmlhttp = server.Createobject("MSXML2.ServerXMLHTTP")
xmlhttp.Open "POST",posturl,false
xmlhttp.setRequestHeader "Content-Type", "application/json"
xmlhttp.setRequestHeader "Authorization", "Your Server key"

xmlhttp.send body
result= xmlhttp.responseText
//response.write result to check Firebase response
Set xmlhttp = nothing
 public class Notification
{
    private string serverKey = "kkkkk";
    private string senderId = "iiddddd";
    private string webAddr = "https://fcm.googleapis.com/fcm/send";

    public string SendNotification(string DeviceToken, string title ,string msg )
    {
        var result = "-1";
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Headers.Add(string.Format("Authorization: key={0}", serverKey));
        httpWebRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
        httpWebRequest.Method = "POST";

        var payload = new
        {
            to = DeviceToken,
            priority = "high",
            content_available = true,
            notification = new
            {
                body = msg,
                title = title
            },
        };
        var serializer = new JavaScriptSerializer();
        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = serializer.Serialize(payload);
            streamWriter.Write(json);
            streamWriter.Flush();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            result = streamReader.ReadToEnd();
        }
        return result;
    }
}

2019更新

有一个新的 .NET Admin SDK 允许您从您的服务器发送通知。 通过 Nuget 安装

Install-Package FirebaseAdmin

然后您必须按照 here 给出的说明下载服务帐户密钥以获取服务帐户密钥,然后在您的项目中引用它。我已经能够通过像这样初始化客户端来发送消息

using FirebaseAdmin;
using FirebaseAdmin.Messaging;
using Google.Apis.Auth.OAuth2;
...

public class MobileMessagingClient : IMobileMessagingClient
{
    private readonly FirebaseMessaging messaging;

    public MobileMessagingClient()
    {
        var app = FirebaseApp.Create(new AppOptions() { Credential = GoogleCredential.FromFile("serviceAccountKey.json").CreateScoped("https://www.googleapis.com/auth/firebase.messaging")});           
        messaging = FirebaseMessaging.GetMessaging(app);
    }
    //...          
}

初始化应用程序后,您现在可以创建通知和数据消息并将它们发送到您喜欢的设备。

private Message CreateNotification(string title, string notificationBody, string token)
{    
    return new Message()
    {
        Token = token,
        Notification = new Notification()
        {
            Body = notificationBody,
            Title = title
        }
    };
}

public async Task SendNotification(string token, string title, string body)
{
    var result = await messaging.SendAsync(CreateNotification(title, body, token)); 
    //do something with result
}

..... 在您的服务集合中,然后您可以添加它...

services.AddSingleton<IMobileMessagingClient, MobileMessagingClient >();

要命中 Firebase API 我们需要来自 Firebase 的一些信息,我们需要 API URL (https://fcm.googleapis.com/fcm/send) 和识别我们的 Firebase 项目安全的唯一密钥原因。

我们可以使用此方法从 .NET Core 后端发送通知:

        public async Task<bool> SendNotificationAsync(string token, string title, string body)
    {
        using (var client = new HttpClient())
        {
            var firebaseOptionsServerId = _firebaseOptions.ServerApiKey;
            var firebaseOptionsSenderId = _firebaseOptions.SenderId;

            client.BaseAddress = new Uri("https://fcm.googleapis.com");
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization",
                $"key={firebaseOptionsServerId}");
            client.DefaultRequestHeaders.TryAddWithoutValidation("Sender", $"id={firebaseOptionsSenderId}");


            var data = new
            {
                to = token,
                notification = new
                {
                    body = body,
                    title = title,
                },
                priority = "high"
            };

            var json = JsonConvert.SerializeObject(data);
            var httpContent = new StringContent(json, Encoding.UTF8, "application/json");

            var result = await _client.PostAsync("/fcm/send", httpContent);
            return result.StatusCode.Equals(HttpStatusCode.OK);
        }
    }

这些参数是:

  • token: 字符串表示 Firebase 在每个 app-installation 上提供的 FCM 令牌。这将是通知将要发送的 app-installation 的列表。
  • title:通知加粗部分
  • body: 表示Firebase SDK的“Message text”字段,这是您要发送给用户的消息。

要找到您的发件人 ID 和 API 密钥,您必须:

  • 登录 Firebase 开发人员控制台并转到您的仪表板
  • 单击“齿轮”图标并访问“项目设置”
  • 前往 “云消息部分”,您将可以访问发件人 ID 和 API 键。

2020/11/28

下载此文件Firebase -> 设置 -> 服务帐户 -> Firebase Admin SDK

将下载的文件移动到您的 dotnet Core Root 文件夹,然后将其名称更改为 key.json 例如。

然后将此代码添加到您的 .csproj 文件中:YourProjectName.csproj 在您的项目根文件夹中:

  <ItemGroup>
    <None Update="key.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
  </ItemGroup>

然后将此代码添加到 Program.csMain 函数中:

var defaultApp = FirebaseApp.Create(new AppOptions()
{
  Credential = 
  GoogleCredential.FromFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, 
  "key.json")),
});

最后一件事是推送通知的代码:

public async Task SendNotificationAsync(string DeviceToken, string title ,string body){
 var message = new Message()
 {
  Notification = new FirebaseAdmin.Messaging.Notification
  {
     Title = title,
     Body = body
  },
  Token = DeviceToken,
 };
 var messaging = FirebaseMessaging.DefaultInstance;
 var result = await messaging.SendAsync(message);
}

把它放在任何控制器中然后你可以调用它来发送通知...

这就是我推送通知所做的,它运行得非常好而且速度很快...

使用 CorePush 库

它非常轻便。我在我的所有项目中都使用它来发送 Firebase Android 和 Apple iOS 推送通知。有用的链接:

  1. NuGet package
  2. Documentation

界面非常简洁:

发送 APN 消息:

var apn = new ApnSender(settings, httpClient);
await apn.SendAsync(notification, deviceToken);

发送 FCM 消息:

var fcm = new FcmSender(settings, httpClient);
await fcm.SendAsync(deviceToken, notification);