如何使用C#创建推送通知(FCM)

时间:2017-07-10 09:09:44

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

我有一个用.NET Core编写的REST Api,现在需要创建一个Push NotificationFirebase Cloud Messaging (FCM)。为了测试,我使用Firebase Console,但我需要以编程方式完成此操作。我已经浏览了Firebase的文档以及谷歌的一些例子,但我更加困惑。

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

2 个答案:

答案 0 :(得分:1)

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

如何获取服务器密钥:以下是帮助的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();
    }
}

答案 1 :(得分: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);
}