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

问题描述 投票:0回答:3

我有一个用 .NET Core 编写的 REST Api,现在需要创建一个

Push Notification
Firebase Cloud Messaging (FCM)
。为了进行测试,我使用
Firebase Console
但我需要以编程方式完成此操作。我已经通过 Google 浏览了 Firebase 的文档和一些示例,但我更加困惑。

我认为可以通过常规

Http
创建一条消息,但是有人可以发布一个简单的工作示例以便我可以接听吗?或者说,我的理解完全错误?

c# .net firebase firebase-cloud-messaging
3个回答
5
投票

借助 .NET Core,您可以将这个轻量级 CorePush 库用于 Firebase Android、iOS、Web 推送通知和 Apple APN HTTP/2 推送通知:

Install-Package CorePush

然后对于 Firebase Web、Android 或 iOS:

var firebaseSettingsJson = await File.ReadAllTextAsync('./project-123.json');
var fcm = new FirebaseSender(firebaseSettingsJson, httpClient);
await fcm.SendAsync(notification);

或通过 HTTP/2 的 APN Apple 推送通知:

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

3
投票

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

如何获取服务器密钥:这是有帮助的问题链接

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

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();
    }
}

0
投票

我正在尝试使用此 NuGet 发送通知,但我对 firebase 一无所知,有人可以给我帮助吗? 我已经在 dll(类库)中安装了这个 NuGet,但我现在不明白我必须做什么。 谢谢你,祝你有美好的一天

© www.soinside.com 2019 - 2024. All rights reserved.