FCM (Firebase Cloud Messaging) Push Notification with Asp.Net

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

C# Server Side Code For 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 and senderId , You get is here---------as follow(Below Images) (go to your firebase App)

Step. 1

Step. 2

Step. 3


2019 Update

There's a new .NET Admin SDK that allows you to send notifications from your server. Install via Nuget

Install-Package FirebaseAdmin

You'll then have to obtain the service account key by downloading it by following the instructions given here, and then reference it in your project. I've been able to send messages by initializing the client like this

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

After initializing the app you are now able to create notifications and data messages and send them to the devices you'd like.

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
}

..... in your service collection you can then add it...

services.AddSingleton<IMobileMessagingClient, MobileMessagingClient >();

To hit Firebase API we need some information from Firebase, we need the API URL (https://fcm.googleapis.com/fcm/send) and unique keys that identify our Firebase project for security reasons.

We can use this method to send notifications from .NET Core backend:

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

These parameters are:

  • token: string represents a FCM token provided by Firebase on each app-installation. This is going to be the list of app-installations that the notification is going to send.
  • title: It’s the bold section of notification.
  • body: It represents “Message text” field of the Firebase SDK, this is the message you want to send to the users.

To find your Sender ID and API key you have to:

  • Login to the Firebase Developer Console and go to your Dashboard
  • Click on the “gear” icon and access “project settings”
  • Go to the “Cloud Messaging Section” and you will have access to the sender ID and the API Key. enter image description here