[英]How to create a Push Notification (FCM) using C#
我有一个用 .NET Core 编写的 REST Api,现在需要创建一个到Firebase Cloud Messaging (FCM)
的Push Notification
。 为了进行测试,我使用的是Firebase Console
,但我需要以编程方式完成此操作。 我已经通过 Google 浏览了 Firebase 的文档和一些示例,但更加困惑。
我认为可以通过常规Http
创建消息,但是有人可以发布一个简单的工作示例以便我可以获取它吗? 或者,也许,我的理解是完全错误的?
有些人也喜欢这个问题,所以想到提供我实施的解决方案,认为它可能对其他人有所帮助。 如果您有任何问题,请随时提问。
如何获取服务器密钥:这是有帮助的问题链接。
可以在此处找到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();
}
}
通过 .NET Core,您可以将这个轻量级库用于 FCM 推送通知和 APN HTTP/2 推送通知:
Install-Package CorePush
然后是 Firebase:
using (var fcm = new FcmSender(serverKey, senderId))
{
await fcm.SendAsync(deviceToken, notification);
}
或接入点:
using (var apn = new ApnSender(privateKey, keyId, teamId, appbundleId, server))
{
await apn.SendAsync(deviceToken, notification);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.