首页 > 解决方案 > FirebaseAdmin FirebaseApp 检查 Firebase 实例是否存在

问题描述

我有一个订阅多个注册主题的 C# 项目。由于项目的性质以及您无法查看有多少人已经订阅了某个主题的事实,我需要对服务器进行以下异步调用:

订阅注册

TopicManagementResponse response = await FirebaseMessaging.DefaultInstance.SubscribeToTopicAsync(registrationTokens, topic);

向主题发送消息

string response = await FirebaseMessaging.DefaultInstance.SendAsync(message);

退订注册

TopicManagementResponse response = await FirebaseMessaging.DefaultInstance.UnsubscribeFromTopicAsync(registrationTokens, topic);

因为有三个调用我需要使用凭据创建 FirebaseApp 的实例:

FirebaseApp.Create(new AppOptions()
{
    Credential = GoogleCredential.FromFile(path),
});

但是因为异步帖子返回“WaitingForActivation”响应(但它确实正确地完成了它应该做的事情)我无法删除实例以继续下一个函数,因为它抛出错误,因为它无法重新创建另一个 FirebaseApp 实例- 如果我给它一个名字,它会失败,所以我不能使用 GetInstance(string name)。

我错过了什么还是有其他方法可以做到这一点。

下面是一个订阅函数的例子:

internal static async Task SubscribeToTopic(string path, string topic, string regID5, string regID)
{
    FirebaseApp app = FirebaseApp.Create(new AppOptions()
    {
        Credential = GoogleCredential.FromFile(path),
    });

    var registrationTokens = new List<string>()
    {
       regID5, regID
    };

    // Subscribe the devices corresponding to the registration tokens to the
    // topic

    try
    {
        TopicManagementResponse response = await FirebaseMessaging.DefaultInstance.SubscribeToTopicAsync(registrationTokens, topic);

        using (StreamWriter sw = System.IO.File.AppendText(HttpContext.Current.Server.MapPath("/tokens.txt")))
        {
            sw.WriteLine($"{response.SuccessCount} tokens were subscribed successfully");
        }

    }
    catch (Exception ex)
    {
        string myerror = ex.Message;
    }

}

有任何想法吗?

标签: c#firebasefirebase-authentication

解决方案


您每次都在创建 firebase 实例。所以你需要在 global.asax 文件的应用程序启动中创建 firebase 实例。


推荐阅读