So I have already set up the project and even tried testing it by adding sample notification from Cloud Messaging and receive that notification in my Android Emulator.
However, when there's changes from the web, I need that to push to the Mobile. So I tried this code in the web:
public void PushNotificationToFCM()
{
try
{
var applicationID = "AIzaSyDaWwl..........";
var senderId = "487....";
string deviceId = "1:487565223284:android:a3f0953e5fbdd790";
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 = "sending to..",
title = "title-----"
}
};
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;
}
}
The response is:
{"multicast_id":7985385082196953522,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
Please help me. Thank you.
I would suggest you check this amazing guide by Nico Bonoro on Medium which explains everything you need to do step by step to configure firebase with a .Net backend
Create a static class called
PushNotificationLogic.cs
with this method:Add a static method called
SendPushNotifications
where these parameters are:For the method, I am going to suppose that all parameters are correct without bad values (you can add all the validations you want). The first thing we have to do is to create an object with all the data we need to send to the API
Add two classes as follows:
Then, just create a new object of type “Message” and serialize it as I did it here:
Note: You will need NewtonSoft.Json added in your project
Now we just need a request to Firebase API and we’re done. The request has to be as a “Post” Method to the Firebase API-Url, we have to add a Header which is “Authorization” and use a value like “key={Your_Server_Key}”. Then we add the content (jsonMessage) and you are ready to hit the API.
Good luck feel free to revert in case of queries.