web-dev-qa-db-fra.com

Notification push FCM (Firebase Cloud Messaging) avec Asp.Net

 FCM

J'ai déjà envoyé le message GCM à Google Server en utilisant asp .net dans la méthode suivante,

Notification push GCM avec Asp.Net

Maintenant, j'ai planifié la mise à niveau vers la méthode FCM, tout le monde a une idée à ce sujet ou le développe dans asp .net laissez-moi savoir ..

9
bgs

C # Code côté serveur Pour Firebase Cloud Messaging

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 et senderId, vous obtenez est ici --------- comme suit (images ci-dessous) (Allez à votre application firebase)

 Step. 1

 Step. 2

 Step. 3

17
Nilesh Panchal
 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;
    }
}
4
EraMaX

Mise à jour 2019

Il existe un nouveau .NET Admin SDK qui vous permet d’envoyer des notifications à partir de votre serveur. Installer via Nuget 

Install-Package FirebaseAdmin

Vous devrez ensuite obtenir la clé du compte de service en la téléchargeant en suivant les instructions données ici , puis en la référençant dans votre projet. J'ai pu envoyer des messages en initialisant le client comme ceci

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);
            }
    ...

    }

Après avoir initialisé l'application, vous pouvez désormais créer des notifications et des messages de données et les envoyer aux appareils de votre choix.

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

..... dans votre collection de services, vous pouvez ensuite l'ajouter ... 

services.AddSingleton<IMobileMessagingClient, MobileMessagingClient >();
2
Alfred Waligo

Voici mon exemple de VbScript pour qui préfère 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
1
Ali Sheikhpour

Je ne pense pas qu'il y ait de changement dans la manière dont vous envoyez les notifications Push. Dans FCM également, vous allez faire une demande HTTP POST de la même manière que vous l'avez faite pour GCM:

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..."
}

Lisez à propos de Serveur FCM pour plus d’informations.

Le seul changement que je pouvais voir maintenant est l'URL cible. Période.

0
Chintan Soni