ASP.NET Core gRPC JSON转码抛出InvalidOperationException问题求助
解决gRPC JSON转码中Google.Api.HttpRule版本冲突问题
核心问题确实是Google.Api.HttpRule类型的程序集版本不匹配:你通过本地Protos/google/api下的.proto文件生成的HttpRule类型属于自定义的Shared程序集(版本1.0.0.0),而Microsoft.AspNetCore.Grpc.JsonTranscoding(7.0.9版本)依赖的是NuGet包Google.Api.CommonProtos中的官方HttpRule类型(版本2.5.0.0),两者类型标识不兼容导致绑定失败。
解决方案(优先推荐方案1)
方案1:移除本地google/api proto文件,改用官方NuGet包定义
- 删除项目中
Protos/google/api目录下的annotations.proto和http.proto文件 - 安装适配的
Google.Api.CommonProtosNuGet包:
(版本选择2.5.0和组件依赖的版本保持一致,避免新的冲突)Install-Package Google.Api.CommonProtos -Version 2.5.0 - 修改你的
Some.proto文件中的导入语句,确保指向NuGet包提供的官方定义:import "google/api/annotations.proto"; import "google/api/http.proto"; - 清理项目的
obj和bin目录,重新生成解决方案
方案2:程序集绑定重定向(临时 workaround,不推荐)
如果必须保留本地的proto文件,可以通过程序集绑定重定向强制统一类型版本:
在项目的app.config或web.config中添加如下配置:
<runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="Google.Api.HttpRule" publicKeyToken="null" culture="neutral" /> <bindingRedirect oldVersion="1.0.0.0" newVersion="2.5.0.0" /> <codeBase version="2.5.0.0" href="Google.Api.CommonProtos.dll" /> </dependentAssembly> </assemblyBinding> </runtime>
注意:这种方式可能引发其他潜在兼容性问题,仅作为临时应急方案使用。
验证步骤
- 重新运行项目,检查是否仍存在类型绑定错误
- 查看生成的gRPC服务代码(如
obj/Debug/net7.0/SomeGrpc.cs),确认HttpRule的引用来自Google.Api.CommonProtos而非自定义的Shared程序集
内容的提问来源于stack exchange,提问作者Mirodil
相关产品推荐
相关产品推荐

