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

.NET 7中gRPC Code First项目添加JSON转码配置的方法咨询

在.NET 7 gRPC Code First项目中配置JSON转码

在Code First模式下,无需在proto文件中编写google.api.http配置,而是通过[GrpcMethod]特性结合Google.Api.HttpRule类来实现JSON转码规则配置,具体步骤如下:

1. 安装依赖包

确保项目引用Google.Api.CommonProtos NuGet包,该包提供了配置HTTP转码必需的HttpRule类型。

2. 为服务方法添加转码配置

在服务接口的目标方法上,添加[GrpcMethod]特性并指定HttpRule属性,以此替代proto文件中的配置逻辑。以你的IReportService为例:

using Google.Api;
using ProtoBuf.Grpc;
using System.ServiceModel;

[ServiceContract]
public interface IReportService
{
    [OperationContract]
    // 配置GET请求路径,对应proto中的google.api.http选项
    [GrpcMethod(HttpRule = new HttpRule { Get = "/v1/reports" })]
    Task<ReportListResponse> Getreports(CallContext context = default);
}

如果方法包含参数(比如根据ID查询报表),可在路径中添加占位符,和proto配置逻辑一致:

[OperationContract]
[GrpcMethod(HttpRule = new HttpRule { Get = "/v1/reports/{reportId}" })]
Task<ReportDetailResponse> GetReportById(int reportId, CallContext context = default);

3. 启用JSON转码服务

在Program.cs中配置gRPC服务时,调用AddJsonTranscoding()启用JSON转码功能:

var builder = WebApplication.CreateBuilder(args);

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

var app = builder.Build();

// 映射你的gRPC服务实现
app.MapGrpcService<ReportService>();

app.Run();

完成以上配置后,你的gRPC服务将同时支持gRPC原生调用和HTTP JSON调用,客户端可通过你指定的路径(如/v1/reports)以JSON格式请求服务。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 19:35:18