如何将我的 MAUI 应用连接到 Firestore 数据库?(通过服务帐户 json 文件)

dbe*_*gan 6 .net c# firebase google-cloud-firestore maui

创建一个 MAUI 应用程序并尝试将其连接到 Firestore。我按照此处的建议下载服务帐户 JSON 文件并设置GOOGLE_APPLICATION_CREDENTIALS环境变量。

我从我的 firebase 项目在线下载了我的服务文件,将其重命名为GoogleAppCredentials.json,然后使用构建操作“MauiAsset”将其包含在我的 MAUI 项目中,如下所示:

GoogleAppCredentials 位置

然后我的 cs 文件引用该文件:

string path = "GoogleAppCredentials.json";
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", path);
Run Code Online (Sandbox Code Playgroud)

但是当我在 Android 模拟器上运行该应用程序时,出现以下错误:

System.AggregateException
  Message=One or more errors occurred. (Error reading credential file from location GoogleAppCredentials.json: Could not find file '/GoogleAppCredentials.json'.
Please check the value of the Environment Variable GOOGLE_APPLICATION_CREDENTIALS)
Run Code Online (Sandbox Code Playgroud)

在 Windows 机器上...

System.AggregateException
  Message=One or more errors occurred. (Error reading credential file from location GoogleAppCredentials.json: Could not find file 'C:\WINDOWS\system32\GoogleAppCredentials.json'.
Please check the value of the Environment Variable GOOGLE_APPLICATION_CREDENTIALS)
Run Code Online (Sandbox Code Playgroud)

那么对于 MAUI,我如何正确复制GoogleAppCredentials.json到应用程序中(如果不是 MauiAsset,还有什么?),然后在.cs文件中引用它?

Rom*_*iak 2

创建一个 MAUI 应用程序并尝试将其连接到 Firestore。我按照此处的建议下载服务帐户 JSON 文件并设置 GOOGLE_APPLICATION_CREDENTIALS 环境变量。

该.NET 客户端用于后端服务。您可以安装它并且它可以开始运行,但它们设计用于 Google Cloud 环境中的 .net 服务。

MAUI 是一个多目标项目,它增加了保存项目中所有代码库的能力,而不是像在 Xamarin 中那样为每个平台添加单独的项目。多目标项目窃取是针对具有平台绑定的特定平台工件构建的。例如,net6.0-android包含与所有标准 Android 生态系统的 Android 绑定。

要与 Firebase Firestore 集成,您需要使用 Android 指南和库:Xamarin.Firebase.Firestore 并使用 GoogleServicesJson 构建操作配置 google-services.json,但在 MAUI 中,您需要在 Platform/Andoroid 位置执行此操作。

我的 csproj 包含此配置

<ItemGroup>
    <None Remove="Platforms\Android\google-services.json" />
</ItemGroup>
<ItemGroup>
    <GoogleServicesJson Include="Platforms\Android\google-services.json" />
</ItemGroup>

Run Code Online (Sandbox Code Playgroud)

对于我的项目,我不以 WinUI 为目标,因此我使用此库来访问 Firestore Plugin.CloudFirestore

  • @AdamB 在 Xamarin.Forms 或 Xamarin 传统中,您需要为每个平台创建单独的项目:**MyApp.Android**、**MyApp.iOS**。它们简单地代表了所有平台特定的代码。这样比较容易理解。在 MAUI 中,您现在拥有带有 Platform 文件夹的项目,该文件夹动态链接特定目标的构建。因此,要配置此类内容,只需使用与您集成的产品相同的指令,但您使用 **Platform/Android** for **MyApp.iOS** 使用**,而不是 **MyApp.Android** 项目平台/iOS**。并搜索 Xamarin.** 包。 (2认同)