我已在以下方法中使用GCM
将asp .net
消息推送到谷歌服务器,
GCM Push Notification with Asp.Net
现在我已计划升级到FCM
方法,任何人都对此有所了解或在asp .net
开发此信息让我知道..
答案 0 :(得分:19)
C#服务器端代码适用于Firebase 云消息传递
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
namespace Sch_WCFApplication
{
public class PushNotification
{
public PushNotification(Plobj obj)
{
try
{
var applicationID = "AIza---------4GcVJj4dI";
var senderId = "57-------55";
string deviceId = "euxqdp------ioIdL87abVL";
WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/json";
var data = new
{
to = deviceId,
notification = new
{
body = obj.Message,
title = obj.TagMsg,
icon = "myicon"
}
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(data);
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));
tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
tRequest.ContentLength = byteArray.Length;
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 sResponseFromServer = tReader.ReadToEnd();
string str = sResponseFromServer;
}
}
}
}
}
catch (Exception ex)
{
string str = ex.Message;
}
}
}
}
APIKey和senderId,你得到的是---------如下(图片下方) (转到你的firebase应用程序)
答案 1 :(得分:7)
public class Notification
{
private string serverKey = "kkkkk";
private string senderId = "iiddddd";
private string webAddr = "https://fcm.googleapis.com/fcm/send";
public string SendNotification(string DeviceToken, string title ,string msg )
{
var result = "-1";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add(string.Format("Authorization: key={0}", serverKey));
httpWebRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
httpWebRequest.Method = "POST";
var payload = new
{
to = DeviceToken,
priority = "high",
content_available = true,
notification = new
{
body = msg,
title = title
},
};
var serializer = new JavaScriptSerializer();
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = serializer.Serialize(payload);
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
}
答案 2 :(得分:6)
2019更新
有一个新的.NET Admin SDK,可让您从服务器发送通知。 通过Nuget安装
Install-Package FirebaseAdmin
然后,您必须按照here的说明进行下载,以获取服务帐户密钥,然后在您的项目中对其进行引用。这样就可以通过初始化客户端来发送消息了
using FirebaseAdmin;
using FirebaseAdmin.Messaging;
using Google.Apis.Auth.OAuth2;
...
public class MobileMessagingClient : IMobileMessagingClient
{
private readonly FirebaseMessaging messaging;
public MobileMessagingClient()
{
var app = FirebaseApp.Create(new AppOptions() { Credential = GoogleCredential.FromFile("serviceAccountKey.json").CreateScoped("https://www.googleapis.com/auth/firebase.messaging")});
messaging = FirebaseMessaging.GetMessaging(app);
}
//...
}
初始化应用程序后,您现在可以创建通知和数据消息并将其发送到您想要的设备。
private Message CreateNotification(string title, string notificationBody, string token)
{
return new Message()
{
Token = token,
Notification = new Notification()
{
Body = notificationBody,
Title = title
}
};
}
public async Task SendNotification(string token, string title, string body)
{
var result = await messaging.SendAsync(CreateNotification(title, body, token));
//do something with result
}
.....在您的服务集合中,您可以添加它...
services.AddSingleton<IMobileMessagingClient, MobileMessagingClient >();
答案 3 :(得分:1)
以下是我更喜欢vb的VbScript示例:
//Create Json body
posturl="https://fcm.googleapis.com/fcm/send"
body=body & "{ ""notification"": {"
body=body & """title"": ""Your Title"","
body=body & """text"": ""Your Text"","
body=body & "},"
body=body & """to"" : ""target Token""}"
//Set Headers :Content Type and server key
set xmlhttp = server.Createobject("MSXML2.ServerXMLHTTP")
xmlhttp.Open "POST",posturl,false
xmlhttp.setRequestHeader "Content-Type", "application/json"
xmlhttp.setRequestHeader "Authorization", "Your Server key"
xmlhttp.send body
result= xmlhttp.responseText
//response.write result to check Firebase response
Set xmlhttp = nothing
答案 4 :(得分:1)
2020/11/28
从 Firebase->设置->服务帐户-> Firebase Admin SDK
下载此文件将下载的文件移至您的dotnet Core Root文件夹,然后将其名称更改为key.json例如。
然后将此代码添加到您的.csproj文件:项目根文件夹中的 YourProjectName.csproj :
<ItemGroup>
<None Update="key.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
然后将此代码添加到 Main 函数中的 Program.cs 中:
var defaultApp = FirebaseApp.Create(new AppOptions()
{
Credential =
GoogleCredential.FromFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
"key.json")),
});
最后是将推送通知的代码:
public async Task SendNotificationAsync(string DeviceToken, string title ,string body){
var message = new Message()
{
Notification = new FirebaseAdmin.Messaging.Notification
{
Title = title,
Body = body
},
Token = DeviceToken,
};
var messaging = FirebaseMessaging.DefaultInstance;
var result = await messaging.SendAsync(message);
}
将其放在任何Controller中,然后您可以调用它以发送通知...
这就是我要推送通知的方法,它运行得非常好而且很快...
答案 5 :(得分:1)
它非常轻巧。我在所有项目中使用它来发送 Firebase Android 和 Apple iOS 推送通知。有用的链接:
界面非常简单和简约:
发送 APN 消息:
var apn = new ApnSender(settings, httpClient);
await apn.SendAsync(notification, deviceToken);
发送 FCM 消息:
var fcm = new FcmSender(settings, httpClient);
await fcm.SendAsync(deviceToken, notification);
答案 6 :(得分:0)
我不相信您发送推送通知的方式有任何变化。在FCM中,您将以与GCM相同的方式进行HTTP POST请求:
https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
{ "data": {
"score": "5x1",
"time": "15:10"
},
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
}
了解更多信息,请阅读FCM Server。
我现在唯一能看到的变化是目标网址。周期。
答案 7 :(得分:0)
要访问Firebase API,我们需要来自Firebase的一些信息,我们需要API URL(https://fcm.googleapis.com/fcm/send)和用于出于安全原因而标识Firebase项目的唯一密钥。
我们可以使用这种方法从.NET Core后端发送通知:
// both letter
if (a.substring(i+1) === b.substring(j+1)) {
// start from space, all same, compare key
condi = a.substring(0,i).localeCompare(b.substring(0,j));
//console.log('same', condi, a.substring(0,i), b.substring(0,j));
return condi;
} else {
condi = a.substring(i+1).localeCompare(b.substring(j+1));
//console.log('not same', condi, a.substring(i+1), ' | ', b.substring(j+1));
return condi;
}
这些参数是:
要找到您的发件人ID和API密钥,您必须: