C# FirebaseMessaging.DefaultInstance.SendAsync 永远不会完成

问题描述 投票:0回答:1

我有一个在 .NET 4.8 中用 C# 构建的 EXE,我需要 “从旧版 FCM API 迁移到 HTTP v1” 继续向 Android 设备发送推送通知。

旧设置不使用 SDK,只是使用标头中的密钥发布到 FCM API。

对于新设置,我添加了 FirebaseAdmin SDK 并导入了 Google.Apis.Auth.OAuth2

问题是,当调用 SendAsync 时(见下文),它永远不会完成。消息未发送。

有什么建议吗?

下面是代码。

    public async Task<string> SendMessage()
    {
        string bericht = "test HTTP v1 GJS";
        string firebaseToken = "a-valid-token";  // real code has a real value

        var scopes = new string[] { "https://www.googleapis.com/auth/firebase.messaging" };
        var path = Path.Combine(Directory.GetCurrentDirectory(), "my-service-account-json-download.json");
        FirebaseApp.Create(new AppOptions()
        {
            Credential = GoogleCredential.FromFile(path).CreateScoped(scopes),
        });

        var message = new Message
        {
            Token = firebaseToken,
            Notification = new Notification
            {
                Title = bericht,
            }
        };
    
        // the following line never finishes!
        string response = await FirebaseMessaging.DefaultInstance.SendAsync(message);
    
        Console.WriteLine("Successfully sent message: " + response);
        return response;
    }
c# firebase push-notification
1个回答
0
投票

我正在使用程序集 Google.Apis.FirebaseCloudMessaging.v1 发送消息:

var credentialJson = HostingEnvironment.MapPath($"myFirebaseFileFromAdminSDK.json"); //get my credentials file

您需要 Google 提供的不记名令牌:

var bearer = "";
var scope = ConfigurationManager.AppSettings["FirebaseCloudMessagingUrl"];
using (var stream = new FileStream(credentialJson, FileMode.Open, FileAccess.Read))
{
    bearer = await GoogleCredential
        .FromStream(stream)
        .CreateScoped(scope)
        .UnderlyingCredential.GetAccessTokenForRequestAsync();
}

创建消息对象传入:

Message msg = new Message
{
    data = new Data(),
};

在 Firebase 控制台中注册设备时添加设备的 Firebase 令牌:

msg.token = "my-firebase-token";

添加一些消息内容(您也可以创建通知对象)

msg.data.title = "your ticket status";
msg.data.body = "64bit-image";

添加消息根对象:

var msgRoot = new Root
{
    message = msg,
    validate_only = false
};

然后送她走...

var url = ConfigurationManager.AppSettings["FirebaseCloudMessagingSendUrl"];

var msgResult = await _httpClient.PostAsync(url, msgRoot, headers =>
{
    headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    headers.Authorization = new AuthenticationHeaderValue("Bearer", bearer);
});

var content = await msgResult.Content.ReadAsStringAsync();
if (msgResult.IsSuccessStatusCode)
{
    return Ok();
}
else
{
    return NotFound();
}
© www.soinside.com 2019 - 2024. All rights reserved.