我有一个使用.NET Core编写的REST API,现在需要创建一个推送通知到Firebase Cloud Messaging (FCM)的功能。为了进行测试,我正在使用Firebase控制台,但我需要以编程方式完成此操作。 我已经阅读了Firebase的文档和一些谷歌的示例,但我感到更加困惑。我认为可以通过常规的Http创建消息,但是能否有人发布一个简单的工作示例,以便我可以学习呢?或者,我的理解完全错误吗?
使用 .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苹果推送通知:
var apn = new ApnSender(settings, httpClient);
await apn.SendAsync(notification, deviceToken);
有些人也喜欢这个问题,所以我想提供我实现的解决方案,希望能帮助其他人。如果您有任何问题,请随时提问。
如何获取服务器密钥:这是一个相关链接可以帮助您。
您可以在Firebase Cloud Messaging文档中找到更多信息。
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();
}
}