[英]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.