Push Notification Using Firebase Cloud Messaging Using .NET
Send Push notification using Firebase Cloud Messaging with .NET. Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably deliver messages at no cost.
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
- To get the keys, log in to Firebase account.
- Select the project from the list.
- Click on "Setting" gear icon and click "Project Settings".
- Click on "Cloud Messaging" tab to select "Server key" and "Sender key" from the below screen.
Add the below code to send push notifications.
-
- WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
- tRequest.Method = "post";
-
- tRequest.Headers.Add(string.Format("Authorization: key={0}", serverKey));
-
- tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
- tRequest.ContentType = "application/json";
- var payload = new {
- to = deviceId,
- priority = "high",
- content_available = true,
- notification = new {
- body = txtmsg,
- title = txttitle.Replace(":", ""),
- sound = "sound.caf",
- badge = badgeCounter
- },
- };
- var serializer = new JavaScriptSerializer();
- Byte[] byteArray = Encoding.UTF8.GetBytes(payload);
- 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()) {
- if (dataStreamResponse != null) using(StreamReader tReader = new StreamReader(dataStreamResponse)) {
- String sResponseFromServer = tReader.ReadToEnd();
- result.Response = sResponseFromServer;
- }
- }
- }
- }