在 Xamarin 中为 Google Cloud API 设置环境变量

Set Environment Variable in Xamarin for Google Cloud API

现在我正在研究如何在 Visual Studio 中使用 Google 的 Cloud Vision API (https://cloud.google.com/dotnet/) 和 Xamarin。我正在用它制作一个 android 应用程序,但我不知道如何为 Cloud API 设置环境变量。 Google 的网站说:

Set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the file path of the JSON file that contains your service account key.

我不太确定该怎么做。我的代码如下。当我 运行 它时,我得到这个错误:

Unhandled Exception:

System.InvalidOperationException: The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information. occurred

我是 C# 的新手,如果这是一个非常简单的修复,我深表歉意。非常感谢您!

public async void AnalyzePicAsync(object sender, EventArgs eventArgs)
{
  string json1 = "";
  //Gets API Credentials
  AssetManager assets = this.Assets;

  using (StreamReader sr = new StreamReader(assets.Open("computer-vision-test-204417-9d2666a5603a.json")))
  {
    json1 = sr.ReadToEnd();
  }
  //Instantiates a client

  GoogleCredential credential = GoogleCredential.FromJson(json1);

  var client = ImageAnnotatorClient.Create();
  // Load the image file into memory
  var image = Image.FromFile(_file.Path);
  // Performs label detection on the image file
  var response = client.DetectLabels(image);
  foreach (var annotation in response)
  {
    if (annotation.Description != null)
        System.Console.WriteLine(annotation.Description);
  }
}

I can't figure out how to set the environment variable for the Cloud API.

根据Getting Started with Authentication,可以使用command prompt

设置
set GOOGLE_APPLICATION_CREDENTIALS=[PATH]

[PATH] 是包含您的服务帐户密钥的 JSON 文件的文件路径。

您可以在 Google 云平台控制台中获取服务帐户密钥。 你可以按照这个 tutorial 来获取它。