You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为现有C# gRPC Server添加JSON Transcoding时遇Google.Api引用错误

解决gRPC JSON Transcoding的CS0234错误及配置问题

问题根源

CS0234错误源于缺少包含Google.Api命名空间的程序集引用,且手动添加的annotations.proto和http.proto未正确生成对应代码,同时项目配置未适配JSON Transcoding需求。

步骤1:替换手动proto文件为NuGet包

不要手动添加google/api下的proto文件,直接安装官方维护的包避免版本冲突:

  • 在GrpcShared项目中安装Google.Api.CommonProtos NuGet包(内置annotations.proto、http.proto等标准proto文件)
  • 删除项目中手动创建的google/api文件夹及其中的文件

步骤2:调整GrpcShared项目配置

修改项目文件(.csproj),确保Protobuf项配置正确,补充必要包引用:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net7.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="CommunityToolkit.Mvvm" Version="8.1.0" />
    <PackageReference Include="Google.Protobuf" Version="3.22.1" />
    <PackageReference Include="Google.Api.CommonProtos" Version="2.15.0" /> <!-- 添加此包 -->
    <PackageReference Include="Grpc.Net.Client" Version="2.52.0" />
    <PackageReference Include="Grpc.Tools" Version="2.53.0">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
  </ItemGroup>

  <ItemGroup>
    <Compile Remove="HelloReply.cs" />
  </ItemGroup>

  <ItemGroup>
    <SupportedPlatform Include="browser" />
    <!-- 调整Protobuf配置,指定GrpcServices为Both(供客户端和服务端共用) -->
    <Protobuf Include="greet.proto" GrpcServices="Both" />
  </ItemGroup>

</Project>

步骤3:确保greet.proto的导入语句正确

在greet.proto中保留标准导入路径,编译器会通过Google.Api.CommonProtos包找到对应文件:

syntax = "proto3";

import "google/api/annotations.proto";

package greet;

service Greeter {
  rpc SayHello (HelloRequest) returns (HelloReply) {
    option (google.api.http) = {
      get: "/v1/greeter/{name}"
    };
  }
}

message HelloRequest {
  string name = 1;
}

message HelloReply {
  string message = 1;
}

步骤4:服务端项目配置JSON Transcoding

在你的gRPC Server项目(非共享类库)中:

  1. 安装Grpc.AspNetCore.JsonTranscoding NuGet包
  2. 在Program.cs中启用JSON转码:
var builder = WebApplication.CreateBuilder(args);

// 添加gRPC服务并启用JSON转码
builder.Services.AddGrpc().AddJsonTranscoding();

var app = builder.Build();

// 映射gRPC服务
app.MapGrpcService<GreeterService>();

// 适配Windows Server 2016,无需强制HTTP/2
app.Run();

关于示例中Protobuf配置的解释

示例里的<Protobuf Include="..\Proto\greet.proto" GrpcServices="Server" Link="Protos\greet.proto" />:

  • Include是proto文件的实际磁盘路径(示例为上级目录的Proto文件夹),你的项目如果用Protos文件夹,可改为Include="Protos/greet.proto"
  • GrpcServices="Server"表示仅生成服务端代码,你的共享类库需兼顾客户端,因此用Both
  • Link是解决方案资源管理器中显示的虚拟路径,用于统一管理文件结构

内容的提问来源于stack exchange,提问作者Exquirentibus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 22:02:36