Cod*_*ute 5 .net c# firebase firebase-cloud-messaging
我有一个用 .NET Core 编写的 REST Api,现在需要创建一个Push Notificationto Firebase Cloud Messaging (FCM). 为了测试,我正在使用Firebase Console但我需要以编程方式完成这项工作。我已经通过 Google 浏览了 Firebase 的文档和一些示例,但更困惑。
我认为可以通过常规创建消息,Http但是有人可以发布一个简单的工作示例以便我可以选择吗?或者,我的理解是完全错误的?
借助 .NET Core,您可以将这个轻量级CorePush 库用于 Firebase Android、iOS、Web 推送通知和 Apple APN HTTP/2 推送通知:
Install-Package CorePush
Run Code Online (Sandbox Code Playgroud)
然后对于 Firebase Web、Android 或 iOS:
var firebaseSettingsJson = await File.ReadAllTextAsync('./project-123.json');
var fcm = new FirebaseSender(firebaseSettingsJson, httpClient);
await fcm.SendAsync(notification);
Run Code Online (Sandbox Code Playgroud)
或者通过 HTTP/2 的 APN Apple 推送通知:
var apn = new ApnSender(settings, httpClient);
await apn.SendAsync(notification, deviceToken);
Run Code Online (Sandbox Code Playgroud)
有些人也喜欢这个问题,所以想到提供我实现的解决方案,认为它可能对其他人有帮助。如果您有任何问题,请随时提问。
如何获取服务器密钥:这是有帮助的问题链接。
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();
}
}
Run Code Online (Sandbox Code Playgroud)