是否可以手动向 SpeechClient 提供 GoogleCredential(在 .NET API 中)?

Is It Possible To Manually Supply a GoogleCredential To SpeechClient (In .NET API)?

我找到的所有 SpeechClient 文档都涉及 运行 下载 SDK 后的命令行,或者笨拙地设置 "GOOGLE_APPLICATION_CREDENTIALS" 环境变量以指向本地凭证文件.

我讨厌环境变量方法,而是想要一个从应用程序根目录加载共享的、源代码控制的开发帐户文件的解决方案。像这样:

var credential = GoogleCredential.FromStream(/*load shared file from app root*/);
var client = SpeechClient.Create(/*I wish I could pass credential in here*/);

有没有办法做到这一点,这样我就不必依赖环境变量了?

是的,通过将 GoogleCredential 转换为 ChannelCredentials,并使用它来初始化 Channel,然后将其包装在 SpeechClient:

using Grpc.Auth;

//...

GoogleCredential googleCredential;
using (Stream m = new FileStream(credentialsFilePath, FileMode.Open))
    googleCredential = GoogleCredential.FromStream(m);
var channel = new Grpc.Core.Channel(SpeechClient.DefaultEndpoint.Host,
    googleCredential.ToChannelCredentials());
var speech = SpeechClient.Create(channel);

更新 2018-02-02 https://cloud.google.com/docs/authentication/production 现在显示了他们向 Google 云服务进行身份验证的所有可能方法,包括像这样的示例.

最新版本SpeechClient.Create没有任何参数。

现在可以使用 SpeechClientBuilder 来实现:

var client = new SpeechClientBuilder { ChannelCredentials = credentials.ToChannelCredentials() }.Build();