Firebase Notification Using C#

In this article, we will explore how to send notifications using C# and Firebase Cloud Messaging (FCM)

What Is Firebase Cloud Messaging (FCM)?

Firebase Cloud Messaging (FCM) is a Cloud solution for messaging or notification for Android, iOS, and Web Applications, that lets you reliably send messages at no cost.

It allows the third-party application developers to send notifications or messages from a server to the user of that application.

Implementation:

  • create the following method to send FCM notification
public void SendMessage()
      {
          string serverKey = "Your Server Key ";
          var notificationInputDto = new
          {
              to = "client Device token",
              body = "Body for your Notification",
              title = "Title for your notificcation",
              icon = ""  
          };
          try
          {
              var result = "";
              var webAddr = "https://fcm.googleapis.com/fcm/send";
              var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
              httpWebRequest.ContentType = "application/json";
              httpWebRequest.Headers.Add("Authorization:key=" + serverKey);
              httpWebRequest.Method = "POST";
              using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
              {                    
                  streamWriter.Write(JsonConvert.SerializeObject(notificationInputDto));
                  streamWriter.Flush();
              }
              var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
              using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
              {
                  result = streamReader.ReadToEnd();
              }             
          }
          catch (Exception ex)
          {
              throw;
          }
      }
  • In the above code replace Your Server key with your legal server key
Note: You have to copy Legacy Server Key from Firebase Console > Project Settings > Cloud Messaging
var notificationInputDto = new
            {
                to = "client Device token",
                body = "Body of your Notification",
                title = "Title of your Notification ",
                icon = ""
            };

In the above code of notificationInputDto replace the values of the properties with your values like :

  • to:-pass Your client’s Device Token.
  • title:- pass the title of the notification.
  • body:- pass the body of the notification.
  • icon:-pass Icon you want to send for your notifications(optional).

Hope this article helps you guys.

Submit a Comment

Your email address will not be published. Required fields are marked *

Footer Logo

Subscribe

Select Categories