I want to send push notifications to a mobile app, so I installed Firebase Admin SDK to my .Net project.
I followed the instructions on Firebase docs, but when I call the SendAsync
from the SDK, it just hangs. Any idea why it would hang? Am I missing steps?
Here is my API code (Note this is only demo code to get it to work):
public async void SendPushNotification()
{
FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.FromFile("path to json file"),
});
var registrationToken = "fqCo_-tXKvY:APA91bGQ47Q2egnqn4Ml...";
var message = new FirebaseAdmin.Messaging.Message()
{
Token = registrationToken,
};
string response = await FirebaseMessaging.DefaultInstance.SendAsync(message);
Console.WriteLine("Successfully sent message: " + response);
}
you have a deadlock because SendAsync will never finish.
if you are calling from ui thread you need to consider using ConfigureAwait(false)
so your snippet will look like below:
public async void SendPushNotification()
{
FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.FromFile("path to json file"),
});
var registrationToken = "fqCo_-tXKvY:APA91bGQ47Q2egnqn4Ml...";
var message = new FirebaseAdmin.Messaging.Message()
{
Token = registrationToken,
};
string response = await FirebaseMessaging.DefaultInstance.SendAsync(message).ConfigureAwait(false);
Console.WriteLine("Successfully sent message: " + response);
}
The firebaseAdmin messaging throw a token error with the .net libraries hence i tested with Postman and works i was able to send the notifications and I see postman generates a code for Resharper library and was easy to install and use, is better to serialize the message with Json and send as parameter
using Firebase.Auth;
using FirebaseAdmin;
using FirebaseAdmin.Auth;
using Google.Apis.Auth.OAuth2;
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using FirebaseAuth = FirebaseAdmin.Auth.FirebaseAuth;
using FirebaseAdmin.Messaging;
using RestSharp;
using Newtonsoft.Json;
namespace messaging
{
class Program
{
static async System.Threading.Tasks.Task Main(string[] args)
{
string token = "dtPMeTshqr??????????????";
var data = new
{
to = token,
notification = new
{
body = "Nueva notificacion de prueba",
title = "Notificacion de prueba",
},
priority = "high"
};
var json = JsonConvert.SerializeObject(data);
Sendmessage(json);
}
private static string Sendmessage(string json)
{
var client = new RestClient("https://fcm.googleapis.com/fcm/send");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "key=AAAAexjc2Qg:APx??????????????");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", json, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
return response.Content;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With