【问题标题】:FCM (Firebase Cloud Messaging) Push Notification with Asp.Net使用 Asp.Net 的 FCM(Firebase 云消息传递)推送通知
【发布时间】:2016-07-04 12:09:37
【问题描述】:

我已经通过以下方法使用asp .net 将GCM 消息推送到谷歌服务器,

GCM Push Notification with Asp.Net

现在我计划升级到FCM 方法,任何人对此有想法或在asp .net 开发此方法让我知道..

【问题讨论】:

  • 我已经使用 .NET admin SDK 来做到这一点。答案是正确的here

标签: android asp.net firebase firebase-cloud-messaging


【解决方案1】:

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 >();

【讨论】:

  • 哇,我无法告诉你我等了多久来自谷歌的官方库。迫不及待想试试这个!感谢您发布此信息,我永远不会知道!
  • SDK +1。应该被接受的答案。让我的代码启动并运行,在找到这篇文章后 10 分钟内发送成功消息。谢谢!
  • IMobileMessagingClient 来自哪个库?它似乎不在 Firebase 库或我能找到的任何其他库中。
  • 这只是我自己决定创建的一个界面,没必要,你可以自己写也可以不使用
  • 我遇到了 ``` FirebaseApp.Create(new AppOptions() { Credential = GoogleCredential.FromFile("serviceAccountKey.json").CreateScoped("googleapis.com/auth/firebase.messaging")}); ```我认为这是由于 CreatedScope 链接出现 404 错误。我使用文档中的 IHostingEnvironment 和 GoogleCredentials 创建消息传递变量 `` var credential = GoogleCredential.FromFile(jsonPath); var app = FirebaseApp.Create(new AppOptions () { Credential = credential }); var messing = FirebaseMessaging.GetMessaging(app); ```
【解决方案2】:

C# 服务器端代码 For 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 应用)

【讨论】:

  • 从哪里获取设备ID?
  • 是使用Service中的FirebaseInstanceId.getInstance().getToken()方法生成的token
  • 想通了.. 服务是 FirebaseInstanceIdService。此外,tRequest.GetResponse() 会抛出“远程服务器返回错误:(401) 未授权”。错误,即使做了这里所说的 -> stackoverflow.com/questions/10205854/… 还有其他解决方案吗?
  • 请使用代码(上面我发布的)而不是你使用的......我希望你通过......没有错误......
  • 而不是使用 web 应用程序中的 api 密钥,而必须使用在项目设置>云消息传递中找到的服务器密钥(而不是旧服务器密钥)。这让它工作了。
【解决方案3】:
 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;
    }
}

【讨论】:

  • 这对于没有 WCF 的 ASP.net C# 非常有用。
  • 嗨,你从哪里得到 devicetoken?
【解决方案4】:

要访问 Firebase API,我们需要来自 Firebase 的一些信息,出于安全原因,我们需要 API URL (https://fcm.googleapis.com/fcm/send) 和唯一的密钥来识别我们的 Firebase 项目。

我们可以使用这种方法从 .NET Core 后端发送通知:

        public async Task<bool> SendNotificationAsync(string token, string title, string body)
    {
        using (var client = new HttpClient())
        {
            var firebaseOptionsServerId = _firebaseOptions.ServerApiKey;
            var firebaseOptionsSenderId = _firebaseOptions.SenderId;

            client.BaseAddress = new Uri("https://fcm.googleapis.com");
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization",
                $"key={firebaseOptionsServerId}");
            client.DefaultRequestHeaders.TryAddWithoutValidation("Sender", $"id={firebaseOptionsSenderId}");


            var data = new
            {
                to = token,
                notification = new
                {
                    body = body,
                    title = title,
                },
                priority = "high"
            };

            var json = JsonConvert.SerializeObject(data);
            var httpContent = new StringContent(json, Encoding.UTF8, "application/json");

            var result = await _client.PostAsync("/fcm/send", httpContent);
            return result.StatusCode.Equals(HttpStatusCode.OK);
        }
    }

这些参数是:

  • token: 字符串表示 Firebase 在每次应用安装时提供的 FCM 令牌。这将是通知要发送的应用安装列表。
  • 标题:这是通知的粗体部分。
  • body:它代表Firebase SDK的“Message text”字段,这是您要发送给用户的消息。

要查找您的发件人 ID 和 API 密钥,您必须:

  • 登录 Firebase 开发者控制台并转到您的仪表板
  • 点击“齿轮”图标并访问“项目设置”
  • 转到 “云消息部分”,您将可以访问发件人 ID 和 API 密钥。

【讨论】:

    【解决方案5】:

    这是我的 VbScript 示例,适合喜欢 vb 的人:

    //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
    

    【讨论】:

      【解决方案6】:

      2020/11/28

      从下载此文件 Firebase -> 设置 -> 服务帐户 -> Firebase Admin SDK

      将下载的文件移动到您的 dotnet Core 根文件夹,然后将其名称更改为 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);
      }
      

      把它放在任何控制器中,然后你就可以调用它来发送通知......

      这就是我为推送通知所做的,它工作得非常好而且很快......

      【讨论】:

      • 在 Program.cs 导入:使用 FirebaseAdmin.Messaging;对于推送通知导入:使用 FirebaseAdmin;使用 Google.Apis.Auth.OAuth2;
      【解决方案7】:

      使用 CorePush 库

      它非常轻巧。我在所有项目中都使用它来发送 Firebase Android 和 Apple iOS 推送通知。有用的链接:

      1. NuGet package
      2. Documentation

      界面非常简洁:

      发送 APN 消息:

      var apn = new ApnSender(settings, httpClient);
      await apn.SendAsync(notification, deviceToken);
      

      发送 FCM 消息:

      var fcm = new FcmSender(settings, httpClient);
      await fcm.SendAsync(deviceToken, notification);
      

      【讨论】:

        【解决方案8】:

        我认为您发送推送通知的方式没有任何变化。同样在 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了解更多信息。

        我现在能看到的唯一变化是目标 URL。期间。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-12-13
          • 1970-01-01
          • 2016-09-21
          • 2017-11-18
          • 2017-03-10
          • 2020-08-14
          • 2022-08-16
          相关资源
          最近更新 更多