环境:
.net6.0
一、准备
安装nuget:
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 greeting
rpc 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调试即可
发表评论