Push Notification Using Firebase Cloud Messaging Using .NET

Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably deliver messages at no cost.

Steps to get server key / SenderID
  1. To get the keys, log in to Firebase account.
  2. Select the project from the list.
  3. Click on "Setting" gear icon and click "Project Settings". 

    .NET

  4. Click on "Cloud Messaging" tab to select "Server key" and "Sender key" from the below screen.

    .NET
Add the below code to send push notifications.
  1. //Create the web request with fire base API  
  2. WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");  
  3. tRequest.Method = "post";  
  4. //serverKey - Key from Firebase cloud messaging server  
  5. tRequest.Headers.Add(string.Format("Authorization: key={0}", serverKey));  
  6. //Sender Id - From firebase project setting  
  7. tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));  
  8. tRequest.ContentType = "application/json";  
  9. var payload = new {  
  10.     to = deviceId,  
  11.         priority = "high",  
  12.         content_available = true,  
  13.         notification = new {  
  14.             body = txtmsg,  
  15.                 title = txttitle.Replace(":"""),  
  16.                 sound = "sound.caf",  
  17.                 badge = badgeCounter  
  18.         },  
  19. };  
  20. var serializer = new JavaScriptSerializer();  
  21. Byte[] byteArray = Encoding.UTF8.GetBytes(payload);  
  22. tRequest.ContentLength = byteArray.Length;  
  23. using(Stream dataStream = tRequest.GetRequestStream()) {  
  24.     dataStream.Write(byteArray, 0, byteArray.Length);  
  25.     using(WebResponse tResponse = tRequest.GetResponse()) {  
  26.         using(Stream dataStreamResponse = tResponse.GetResponseStream()) {  
  27.             if (dataStreamResponse != null) using(StreamReader tReader = new StreamReader(dataStreamResponse)) {  
  28.                 String sResponseFromServer = tReader.ReadToEnd();  
  29.                 result.Response = sResponseFromServer;  
  30.             }  
  31.         }  
  32.     }  
  33. }  
Ebook Download
View all
Learn
View all