Grpc.Auth:无法从程序集“ Grpc.Core.Api”加载类型“ Grpc.Core.CallCredentials”

时间:2019-06-21 18:47:21

标签: c# authentication .net-core google-cloud-platform grpc

上下文

我正在尝试使用Google的Cloud Natural Language API。我有我的服务帐户密钥JSON文件,并尝试编写一个简单的.NET Core应用程序(更具体地说是使用.NET Core的Azure函数),该应用程序将接收一些文本并使用Natural Language API中的情感分析功能并返回几个价值观。

我的实现基于Google文档,尤其是标题下的代码部分:

Passing the path to the service account key in code

以下是我的应用程序:

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>

问题

运行此命令时,出现以下错误:

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(),这似乎是发生错误的方法。

3 个答案:

答案 0 :(得分:2)

  

更具体地说,是使用.NET Core的Azure函数

不幸的是,这就是问题所在。

至少在 emulator 中,存在一个问题,即该仿真器包含的Grpc.Core版本低于1.21.0。通常,只有在使用新功能的情况下这才是问题,但是在1.19.0(IIRC)左右,Grpc.Core被分为Grpc.Core和Grpc.Core.Api,类型转发处理了兼容性问题。没问题,直到您使用期望要显示的拆分代码,但发现原来的Grpc.Core版本已被加载。

issue has been reported to Microsoft,但我尚未看到任何解决方法。请注意,您甚至都不需要直接引用Google.Apis.AuthGrpc.Auth-请参阅我在该问题的最终评论中发布的副本。

答案 1 :(得分:2)

除了上述@JonSkeet的答案之外,链接(https://github.com/Azure/azure-functions-host/issues/4527)还提供了一种解决方法,可将以下行添加到Azure Function .csproj文件中,以解决当前问题:

<Target Name="PostBuild" AfterTargets="PostBuildEvent">
   <!--https://github.com/Azure/azure-functions-host/issues/3568-->
   <!--<Exec Command="copy $(OutDir)bin\runtimes\win\lib\netstandard2.0\System.Private.ServiceModel.dll $(OutDir)bin\System.Private.ServiceModel.dll" />-->
   <Exec Command="copy $(OutDir)$(ProjectName).deps.json $(OutDir)bin\function.deps.json" />
 </Target>
 <Target Name="PostPublish" BeforeTargets="AfterPublish">
   <!--https://github.com/Azure/azure-functions-host/issues/3568-->
   <!--<Exec Command="copy $(PublishDir)bin\runtimes\win\lib\netstandard2.0\System.Private.ServiceModel.dll $(PublishDir)bin\System.Private.ServiceModel.dll" />-->
   <Exec Command="copy $(PublishDir)$(ProjectName).deps.json $(PublishDir)bin\function.deps.json" />
 </Target>

答案 2 :(得分:1)

我遇到了同样的问题,我不得不升级我的包裹

"Microsoft.NET.Sdk.Functions" Version="1.0.29" -> "Microsoft.NET.Sdk.Functions" Version="1.0.31"