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

Col*_*lin 5 .net c# google-cloud-platform google-speech-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*/);
Run Code Online (Sandbox Code Playgroud)

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

Jef*_*nie 13

是的,通过转换GoogleCredential为a ChannelCredentials,并使用它来初始化a 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);
Run Code Online (Sandbox Code Playgroud)

更新2018-02-02 https://cloud.google.com/docs/authentication/production现在显示了向Google Cloud Service进行身份验证的所有可能方式,包括此类示例.

  • 我想到了.我必须引用名称空间Grpc.Auth来获取扩展方法. (3认同)