【问题标题】:Google cloud translator .net client谷歌云翻译.net客户端
【发布时间】:2017-11-11 05:43:17
【问题描述】:

我正在尝试在我的 .net 项目中使用谷歌翻译 api。我已经安装了这个库

安装包 Google.Cloud.Storage.V1

在我的代码中我正在尝试这个

Console.OutputEncoding = System.Text.Encoding.Unicode;
TranslationClient client = TranslationClient.Create();
var response = client.TranslateText("Hello World.", "ru");
Console.WriteLine(response.TranslatedText);

我收到身份验证错误,我真的很困惑如何做到这一点。我不能按原样将 api 密钥传递给 create 函数吗?或者这是一个问题?

我看到 Create 函数有一个选项

GoogleCredential.FromJson(parmas)

但是我可以在其中传递一个 json 字符串吗?如果是,该 JSON 的格式应该是什么?

提前致谢。

【问题讨论】:

  • 你试过文档了吗?
  • 是的,我试过了,但从那里听不懂。

标签: c# google-cloud-storage google-translate


【解决方案1】:

以下是示例应用程序:
https://github.com/GoogleCloudPlatform/dotnet-docs-samples

认证信息:
https://cloud.google.com/docs/authentication/
https://cloud.google.com/docs/authentication/api-keys

首先安装 NuGet 包:
PM> install-package Google.Cloud.Translation.V2 -pre

这是对我有用的绝对最简单的代码。 3行代码,还不错:)

var service = new TranslateService(new BaseClientService.Initializer { ApiKey = apiKeyTranslate });
var client = new TranslationClientImpl(service, TranslationModel.ServiceDefault);
var result = client.TranslateText("Hello, World", "sr");

Response.Write(result.TranslatedText);

【讨论】:

    【解决方案2】:

    请参阅此链接 - https://developers.google.com/identity/protocols/application-default-credentials。下载 .json 文件。

    安装 Google.Cloud.Translation.V2

    string credential_path = @"D:\..\..\cred.json";
    System.Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", credential_path);                                          
    

    【讨论】:

    • 即使在 Web 应用程序中也可以使用,但需要在本地文件系统上保存一个高安全性文件:对于部署到托管环境来说不是最佳选择。使用“应用程序密钥”可以替代,但不是简单的示例。
    猜你喜欢
    • 2018-03-26
    • 2019-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-21
    • 1970-01-01
    • 2020-09-25
    • 2018-07-15
    相关资源
    最近更新 更多