环境:
.net6.0
一、准备
安装nuget:
Grpc.AspNetCore
Google.Protobuf
Grpc.Core.Api
Grpc.Tools
Grpc.AspNetCore.Server.Reflection
Program.cs:
public class Program{public static void Main(string[] args){var builder = WebApplication.CreateBuilder(args);// Additional configuration is required to successfully run gRPC on macOS.// For instructions on how to configure Kestrel and gRPC clients on macOS, visit https://go.microsoft.com/fwlink/?linkid=2099682// Add services to the container.builder.Services.AddGrpc();builder.Services.AddGrpcReflection();//添加gRPC反射var app = builder.Build();IWebHostEnvironment env = app.Environment;// Configure the HTTP request pipeline.app.MapGrpcService<GreeterService>();if (env.IsDevelopment()){//映射gRPC反射服务app.MapGrpcReflectionService();}app.MapGet("/", () => "Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");app.Run();}}
greet.proto:
syntax = "proto3";option csharp_namespace = "Grpc.Common";package greet;// The greeting service definition.
service Greeter {// Sends a greetingrpc SayHello (HelloRequest) returns (HelloReply);
}// The request message containing the user's name.
message HelloRequest {string name = 1;
}// The response message containing the greetings.
message HelloReply {string message = 1;
}
GreeterService :
public class GreeterService : Greeter.GreeterBase{private readonly ILogger<GreeterService> _logger;public GreeterService(ILogger<GreeterService> logger){_logger = logger;}public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context){return Task.FromResult(new HelloReply{Message = "Hello " + request.Name});}}
二、postman调用Grpc
输入grpc主机和port,不需要输入http、https,点击右侧下拉框,点击Use server reflection会自动反射Grpc服务接口,Invoke调试即可