Context
我正在尝试使用 Google 的 Cloud Natural Language API。我有我的服务帐户密钥 JSON 文件,并且正在尝试编写一个简单的 .NET Core 应用程序(更具体地说是使用 .NET Core 的 Azure 函数),该应用程序将接收一些文本并使用 Natural Language API 中的情感分析函数并返回几个值。
我的实现基于 Google 的文档,特别是标题下的代码部分:
将路径传递到代码中的服务帐户密钥 https://cloud.google.com/docs/authentication/production#obtaining_and_providing_service_account_credentials_manually
以下是我的申请:
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Google.Cloud.Language.V1;
using Google.Apis.Auth.OAuth2;
using Grpc.Auth;
namespace Project.Function
{
public static class GoogleNLAPI
{
[FunctionName("GoogleNLAPI")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Admin, "get", "post", Route = null)] HttpRequest req,
ILogger log,
ExecutionContext context)
{
string content = req.Query["content"];
var path = Path.Combine(context.FunctionAppDirectory, "{FILE-NAME}");
var credential = GoogleCredential.FromFile(path)
.CreateScoped(LanguageServiceClient.DefaultScopes);
var channel = new Grpc.Core.Channel(
LanguageServiceClient.DefaultEndpoint.ToString(),
credential.ToChannelCredentials()
);
var languageClient = LanguageServiceClient.Create(channel);
var response = languageClient.AnalyzeSentiment(new Document()
{
Content = content,
Type = Document.Types.Type.PlainText
});
var sentiment = response.DocumentSentiment;
return new OkObjectResult($"Score: {sentiment.Score}\nMagnitude: {sentiment.Magnitude}");
}
}
}
和 .csproj 文件:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
<AzureFunctionsVersion>v2</AzureFunctionsVersion>
<RootNamespace>google_nl_api</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="1.0.28"/>
<PackageReference Include="Google.Cloud.Language.V1" Version="1.2.0"/>
<PackageReference Include="Google.Apis.Auth" Version="1.40.2"/>
<PackageReference Include="Grpc.Auth" Version="1.21.0"/>
</ItemGroup>
<ItemGroup>
<None Update="host.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="{FILE-NAME}">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="local.settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</None>
</ItemGroup>
</Project>
Issue
当我运行这个时,我收到以下错误:
Exception while executing function: GoogleNLAPI. Grpc.Auth: Could not load type 'Grpc.Core.CallCredentials' from assembly 'Grpc.Core.Api, Version=1.0.0.0, Culture=neutral, PublicKeyToken=d754f35622e28bad'.
我正在使用 Grpc.Auth 因为没有它我无法使用.ToChannelCredentials()
,这似乎是发生错误的方法。