【问题标题】:How to create a Push Notification (FCM) using C#如何使用 C# 创建推送通知 (FCM)
【发布时间】:2017-12-13 22:45:31
【问题描述】:

我有一个在.NET核心编写的REST API,现在有要求在Firebase Cloud Messaging (FCM)上创建Push Notification。用于测试,我正在使用Firebase Console但我需要在以编程方式完成此操作。我通过谷歌经历了Firebase的文件和一些例子,但更困惑。

我认为可以通过常规 Http 创建消息,但有人可以发布一个简单的工作示例以便我可以拿起它,好吗?或者,我的理解完全错误?

【问题讨论】:

  • 您现在可以使用 .net Admin SDK(无 http)进行操作,请参阅我的回答 here

标签: c# .net firebase firebase-cloud-messaging


【解决方案1】:

借助 .NET Core,您可以将这个轻量级 library 用于 FCM 推送通知和 APN HTTP/2 推送通知:

Install-Package CorePush

然后是 Firebase:

using (var fcm = new FcmSender(serverKey, senderId))
{
    await fcm.SendAsync(deviceToken, notification);
}

或 APN:

using (var apn = new ApnSender(privateKey, keyId, teamId, appbundleId, server)) 
{
    await apn.SendAsync(deviceToken, notification);
}

【讨论】:

    【解决方案2】:

    有些人也喜欢这个问题,所以想提供我实施的解决方案,认为它可能对其他人有所帮助。如果您有任何问题,请随时提出问题。

    如何获取服务器密钥:这里是question link,它有帮助。

    Firebase 云消息传递文档可以在 here 找到。

    public class FirebaseNotificationModel
    {
        [JsonProperty(PropertyName = "to")]
        public string To { get; set; }
    
        [JsonProperty(PropertyName = "notification")]
        public NotificationModel Notification { get; set; }
    }
    
    
    using System.Net.Http;
    using System.Text;
    public static async void Send(FirebaseNotificationModel firebaseModel)
    {
        HttpRequestMessage httpRequest = null;
        HttpClient httpClient = null;
    
        var authorizationKey = string.Format("key={0}", "YourFirebaseServerKey");
        var jsonBody = SerializationHelper.SerializeObject(firebaseModel);
    
        try
        {
            httpRequest = new HttpRequestMessage(HttpMethod.Post, "https://fcm.googleapis.com/fcm/send");
    
            httpRequest.Headers.TryAddWithoutValidation("Authorization", authorizationKey);
            httpRequest.Content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
    
            httpClient = new HttpClient();
            using (await httpClient.SendAsync(httpRequest))
            {
            }
        }
        catch
        {
            throw;
        }
        finally
        {
            httpRequest.Dispose();
            httpClient.Dispose();
        }
    }
    

    【讨论】:

    • 我知道你发布这篇文章已经 2.5 年了,但是接收来自预定义主题的内容怎么样?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多