【问题标题】:Is It Possible To Manually Supply a GoogleCredential To SpeechClient (In .NET API)?是否可以手动向 SpeechClient 提供 GoogleCredential(在 .NET API 中)?
【发布时间】:2017-08-09 12:09:45
【问题描述】:

我发现的所有 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*/);

有没有办法让我不必依赖环境变量?

【问题讨论】:

标签: c# .net google-cloud-platform google-speech-api


【解决方案1】:

是的,通过将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 云服务进行身份验证的方法,包括这样的示例。

【讨论】:

  • ToChannelCredentials() 来自哪里?我显然缺少参考资料或其他版本。
  • 我想通了。我必须引用命名空间 Grpc.Auth 来获取扩展方法。
  • 您还需要安装 Grpc.Auth Nuget 包。
  • 我在尝试这个时遇到错误:System.TypeLoadException: Could not resolve type with token 0100003e (from typeref, class/assembly System.Runtime.Loader.AssemblyLoadContext, System.Runtime.Loader, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a) 有什么想法吗?
  • 如果我使用示例中给出的方法,我有一个“超过期限”错误。如果我使用相同的 json 文件在代码中手动设置 env 变量,它可以工作,知道为什么吗?
【解决方案2】:

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

现在可以使用 SpeechClientBuilder 来实现:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多