【问题标题】:Using FCM with Asp.net web api 2将 FCM 与 Asp.net web api 2 一起使用
【发布时间】:2018-07-20 05:44:12
【问题描述】:
我已经构建了一个 web api,它将作为 AngularJs、IOS 和 Android 前端应用程序的后端。
现在我需要将通知从我的 web api 推送到前端应用程序,例如当产品更新时。
我正在考虑使用 SignalR 实时推送通知,但如果其他用户离线,它就没有用了。
现在我打算使用 FCM 推送通知,所以请你回答我的问题
如何将我的 web api 与 FCM 集成,使用 FCM 推送通知有什么好处?
PS
如果有任何关于将 asp.net web api 与 FCM 集成的参考资料,我将不胜感激
【问题讨论】:
标签:
c#
asp.net-web-api
push-notification
firebase-cloud-messaging
【解决方案1】:
让我们创建控制台应用程序如下:
class Program
{
static void Main(string[] args)
{
string resend ;
do
{
WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/json";
var objNotification = new
{
to = "Token the device you want to push notification to",
data = new
{
title = "title",
body = "body",
icon = "/firebase-logo.png"
}
};
string jsonNotificationFormat = Newtonsoft.Json.JsonConvert.SerializeObject(objNotification);
Byte[] byteArray = Encoding.UTF8.GetBytes(jsonNotificationFormat);
tRequest.Headers.Add(string.Format("Authorization: key={0}", "your authorization key"));
tRequest.Headers.Add(string.Format("Sender: id={0}", "your senderId"));
tRequest.ContentLength = byteArray.Length;
tRequest.ContentType = "application/json";
using (Stream dataStream = tRequest.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
using (WebResponse tResponse = tRequest.GetResponse())
{
using (Stream dataStreamResponse = tResponse.GetResponseStream())
{
using (StreamReader tReader = new StreamReader(dataStreamResponse))
{
String responseFromFirebaseServer = tReader.ReadToEnd();
FCMResponse response = Newtonsoft.Json.JsonConvert.DeserializeObject<FCMResponse>(responseFromFirebaseServer);
if (response.success == 1)
{
Console.WriteLine("succeeded");
}
else if (response.failure == 1)
{
Console.WriteLine("failed");
}
}
}
}
}
resend = Console.ReadLine();
} while (resend == "c");
}
}
public class FCMResponse
{
public long multicast_id { get; set; }
public int success { get; set; }
public int failure { get; set; }
public int canonical_ids { get; set; }
public List<FCMResult> results { get; set; }
}
public class FCMResult
{
public string message_id { get; set; }
}