1. Introduction

gRPC is an open source, cross-language, high-performance remote procedure call (RPC) framework from Google. gRPC enables client and server applications to communicate transparently and simplifies the construction of connected systems. It uses HTTP/2 as the communication protocol and Protocol Buffers as the serialization protocol.

Its main advantages:

  • Modern high performance lightweight RPC frame.
  • A prioritized API development that uses Protocol Buffers as the description language by default, allowing language-independent implementations.
  • Tools that can be used in multiple languages ​​to generate strongly typed servers and clients.
  • Support client, server bidirectional stream call.
  • Reduce network usage with Protocol Buffers binary serialization.
  • Transfer using HTTP/2

These advantages make gRPC very suitable:

  • High-Performance Lightweight Microservices – Designed for low latency and high throughput communications, gRPC is ideal for lightweight microservices that require high performance.
  • Multi-language hybrid development – gRPC tools support all popular development languages, making gRPC an ideal choice for multi-language development environments.
  • Point-to-point real-time communication – gRPC provides excellent support for bidirectional stream calls. The gRPC service can push messages in real time without polling.
  • Network Restricted Environment – Using Protocol Buffers to serialize messages, the serialization is always smaller than the equivalent JSON message, and the network bandwidth requirement is smaller than JSON.

The scenario of using gRPC is not recommended:

  • Browser accessible API – Browser does not fully support gRPC. Although gRPC-Web can provide browser support, it has limitations and introduces a server proxy.
  • Broadcast real-time communication – gRPC supports real-time communication via streaming, but there is no concept of broadcasting messages to registered connections
  • Interprocess communication – Processes must host HTTP/2 to accept incoming gRPC calls. For Windows, interprocess communication pipes are a faster method.

Excerpt from
Microsoft official documentation

The supported languages ​​are as follows:


2. gRPC on .NET Core

gRPC is now very easy to use in .NET Core and ASP.NET Core, the open source address for implementation on .NET Core:

, which is currently officially ASP. The NET project staff is maintained and has good access to the .NET Core ecosystem.

The gRPC features of .NET Core are as follows:

  • Grpc.AspNetCore

    A framework for hosting gRPC services on ASP.NET Core, integrating gRPC and ASP.NET Core functionality such as logging, dependency injection, authentication and authorization.

  • Grpc.Net.Client is

    based on HttpClient (HttpClient now supports HTTP/2) gRPC client

  • Grpc.Net.ClientFactory

    integrated with the gRPC client HttpClientFactoryallows centralized configuration of gRPC clients and injection into the application using DI

Create a gRPC service using ASP.NET Core

  1. The gRPC service can be quickly created with the templates provided by Visual Studio 2019 (16.3.0).


Come and pull what the default source contains.

1 configuration file appsettings.json, more Kestrel enables HTTP/2 configuration, because gRPC is based on HTTP/2 communication


② PB protocol file greet.protoused to automatically generate a service, the client and the message (represented by data transfer) in C # Class


③ service class GreeterService, service class integrated Greeter.GreeterBasefrom proto automatically generates the file, the generated class obj\Debug\netcoreapp3.0catalog


Automatically generated class:


Startup.csClass 4 , adding the gRPC service to the endpoint route


5 csproj project file containing proto file references


2. Run

The first run will prompt you to trust the certificate, click “Yes”



This is because HTTP/2 requires HTTPS. Although the HTTP/2 protocol does not explicitly require HTTPS, HTTPS is required for browser implementation in security, so HTTP/2 and HTTPS are basically a pair.


Create a gRPC client

1. Add a .NET Core Console Application

2. Add packages via nuget: Grpc.Net.Client, Google.Protobuf, Grpc.Tools


3. Copy the service’s proto file to the client


4. Edit the client project file and add a description about the proto file.

    <Protobuf Include="Protos\greet.proto" GrpcServices="Client" />

Note that GrpcServices=”Client”this is the Client and the service is not the same

5. Generate client projects can generate classes through proto files

6. Add client call code

static async Task Main(string[] args)
    var channel = GrpcChannel.ForAddress("https://localhost:5001");
    var client = new Greeter.GreeterClient(channel);
    var reply = await client.SayHelloAsync(
        new HelloRequest { Name = "晓晨" });
    Console.WriteLine("Greeter 服务返回数据: " + reply.Message);

7. Start the service first, then run the client


Here you can see that the client successfully called the service and received the returned message.

5. Write a service by yourself

The Greeter service we used earlier was created automatically by the template, now let’s write a service ourselves.

Write a “cat service”

1. Define the proto file LuCat.protoand add a description to the csproj project file

syntax = "proto3";

option csharp_namespace = "AspNetCoregRpcService";

import "google/protobuf/empty.proto";
package LuCat; //

//defien service
service LuCat{
    rpc SuckingCat(google.protobuf.Empty) returns(SuckingCatResult);

message SuckingCatResult{
    string message=1;

2. Realize the service LuCatService.cs

public class LuCatService:LuCat.LuCatBase
    private static readonly List<string> Cats=new List<string>(){"英短银渐层","英短金渐层","美短","蓝猫","狸花猫","橘猫"};
    private static readonly Random Rand=new Random(DateTime.Now.Millisecond);
    public override Task<SuckingCatResult> SuckingCat(Empty request, ServerCallContext context)
        return Task.FromResult(new SuckingCatResult()
            Message = $"您吸了一只{Cats[Rand.Next(0, Cats.Count)]}"

3. StartupRegistration endpoint route


4. Add client calls

var catClient = new LuCat.LuCatClient(channel);
var catReply = await catClient.SuckingCatAsync(new Empty());
Console.WriteLine("调用撸猫服务:"+ catReply.Message);

5. Run the test


Six. Practical skills

Tip 1

In the steps in the previous section, we need to copy proto between the service and the client, which is a step that can be omitted.

1. Copy the Protos folder to the solution root directory (the directory where the sln file is located)


2. Delete the Protos folder in the client and service project

3. Add a description about the proto file in the client project file csproj

    <Protobuf Include="..\..\Protos\greet.proto" GrpcServices="Client" Link="Protos\greet.proto" />

4. Add a description about the proto file in the service project file csproj

    <Protobuf Include="..\..\Protos\greet.proto" GrpcServices="Server" Link="Protos\greet.proto" />

In the actual project, please calculate the relative path by yourself.

5. These two projects are all using a proto file, just use this file to maintain.


Tip 2

We use it in actual projects, there must be multiple proto files, do we have to update the csproj file every time we add a proto file?

We can use the MSBuild variable to help us complete, we will introduce the proto file information in the csproj project file to modify.


    <Protobuf Include="..\..\Protos\*.proto" GrpcServices="Server" Link="Protos\%(RecursiveDir)%(Filename)%(Extension)" />


    <Protobuf Include="..\..\Protos\*.proto" GrpcServices="Client" Link="Protos\%(RecursiveDir)%(Filename)%(Extension)" />




gRPC is currently a very mature high-performance RPC framework. The current ecology is very good. Many companies’ products or open source projects are using gRPC. With it, I believe it will make it easier for us to build .NET Core. Microservices allow .NET Core to better access the gRPC ecosystem. I have to say that this is one of the most exciting features of .NET Core 3.0.

Reference materials:

If you can’t access the proto3 documentation, here’s an
offline web version

(please save it as a download and open it with Chrome)

Orignal link:https://www.cnblogs.com/stulzq/p/11581967.html