【问题标题】:How to make a C# REST request using a Google Cloud JSON Service account file?如何使用 Google Cloud JSON 服务帐户文件发出 C# REST 请求?
【发布时间】:2025-12-07 13:20:02
【问题描述】:

我想通过一个简单的休息请求来利用新的 Google TTS。为此,我创建了一个服务帐户,它下载了一个 JSON 文件,其中包含一个私钥 ID、一个私钥、客户端电子邮件、客户端 ID、client_x509_cert_url 等。

我还为系统设置了环境变量:

 Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", jsonFile);

然后我发现了这个使用 Google 提供的 WaveNet TTS 引擎的示例 CURL 请求:

curl -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
--data "{
'input':{
  'text':'Android is a mobile operating system developed by Google,
     based on the Linux kernel and designed primarily for
     touchscreen mobile devices such as smartphones and tablets.'
},
'voice':{
  'languageCode':'en-gb',
  'name':'en-GB-Standard-A',
  'ssmlGender':'FEMALE'
},
'audioConfig':{
  'audioEncoding':'MP3'
}
}" "https://texttospeech.googleapis.com/v1beta1/text:synthesize" > writtenfile.txt

我想从上面的 CURL 请求创建一个简单的 C# webrequest,但是 "gcloud auth application-default print-access-token" 这行对我来说是个问题。我无法在这台机器上安装 CLI gcloud 实例。没有办法从 JSON 服务帐户文件设置 webrequest 授权访问令牌吗?当然,我不必安装 gcloud。

寻找代码示例,演示如何在不使用 gcloud 的情况下使用服务帐户 json 文件将 CURL 代码转换为 C# REST 请求。

【问题讨论】:

  • 不确定您的具体情况,但我使用了类似GoogleCredential googleCredential = GoogleCredential.FromJson(Constants.CRED_JSON); Channel channel = new Channel(SpeechClient.DefaultEndpoint.Host, googleCredential.ToChannelCredentials()); 的方式连接到谷歌语音服务

标签: c# rest gcloud


【解决方案1】:

如果您不想安装 gcloud 软件包,可以使用 API 密钥 执行 REST 调用。这些键可以是created directly in the GCP console,它们可以作为参数通过请求头传递;这样,您可以在不需要gcloud 的情况下对服务进行身份验证。此外,我建议您查看此guide,其中包含使用 C# 发出 REST 请求所需的步骤。

您可以使用此Restlet Client tool 来测试以下示例:

REST 内容示例

  • 标题

https://texttospeech.googleapis.com/v1beta1/text:synthesize?key=<YOUR_API_KEY>

  • 身体

{ 'input':{ 'text':'Android is a mobile operating system developed by Google, based on the Linux kernel and designed primarily for touchscreen mobile devices such as smartphones and tablets.' }, 'voice':{ 'languageCode':'en-gb', 'name':'en-GB-Standard-A', 'ssmlGender':'FEMALE' }, 'audioConfig':{ 'audioEncoding':'MP3' } }

最后,如果您想使用服务帐户 JSON 文件,您可以使用 客户端库create and send your TTS requests 再到 authenticate them directly from your code;但是,此方法需要安装 TextToSpeech 包。

【讨论】: