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

求询.NET Framework 4.7下gRPC.Core服务端实现示例

.NET Framework 4.7 中 gRPC.Core 服务端实现方案

前置依赖安装

  • 给项目安装以下 NuGet 包:Grpc.Core(建议选2.46.x及以下版本,更高版本已停止对.NET Framework的支持)、Google.Protobuf、Grpc.Tools

完整实现步骤

1. 定义 gRPC 协议文件

创建Greeter.proto文件,写入服务和消息定义:

syntax = "proto3";

package greet;

service Greeter {
  rpc SayHello (HelloRequest) returns (HelloReply);
}

message HelloRequest {
  string name = 1;
}

message HelloReply {
  string message = 1;
}

2. 配置代码自动生成

在项目的.csproj文件中添加如下配置,让Grpc.Tools自动生成服务端代码:

<ItemGroup>
  <Protobuf Include="Greeter.proto" GrpcServices="Server" />
</ItemGroup>

3. 实现服务业务逻辑

继承生成的基类,实现具体的服务方法:

using Grpc.Core;
using greet;

public class GreeterService : Greeter.GreeterBase
{
    public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
    {
        return Task.FromResult(new HelloReply
        {
            Message = $"Hello, {request.Name}!"
        });
    }
}

4. 启动 gRPC 服务器

在应用入口(如Program.cs)中初始化并启动服务:

using Grpc.Core;

class Program
{
    static void Main(string[] args)
    {
        const int ListenPort = 50051;
        
        var server = new Server
        {
            Services = { Greeter.BindService(new GreeterService()) },
            Ports = { new ServerPort("localhost", ListenPort, ServerCredentials.Insecure) }
        };
        
        server.Start();
        Console.WriteLine($"gRPC 服务已启动,监听端口 {ListenPort}");
        Console.WriteLine("按任意键停止服务...");
        Console.ReadKey();
        
        server.ShutdownAsync().Wait();
    }
}

关键提示

  • gRPC.Core已进入维护模式,官方不再更新,所以在.NET Framework 4.7环境下务必选择兼容的稳定版本
  • 当前定义的.proto文件可以直接复用在后续.NET 6的Grpc.AspNetCore服务中,降低迁移时的重复工作量

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 22:55:17