Specific methods of using grpc in asp.net core 3.0


I. Introduction

Grpc is a Google open source, cross language, high-performance remote procedure call (RPC) framework. Grpc enables client and server applications to communicate transparently and simplifies the construction of the connection system. It uses http / 2 as the communication protocol and protocol buffers as the serialization protocol.

Its main advantages:

  • Modern high performance lightweight RPC framework.
  • The API development with the priority of agreement uses Protocol Buffers as the description language by default, allowing language independent implementation.
  • Can be used in a variety of language tools to generate strongly typed servers and clients.
  • Support client and server two-way flow calls.
  • Reduce network usage through protocol buffers binary serialization.
  • Transport using HTTP / 2

These advantages make grpc very suitable for:

  • High performance lightweight microservices grpc is designed for low latency and high throughput communication, which is very suitable for lightweight microservices requiring high performance.
  • Multi language hybrid development – grpc tools support all popular development languages, making grpc an ideal choice for multi language development environment.
  • Point to point real-time communication – grpc provides excellent support for two-way flow calls. The grpc service can push messages in real time without polling.
  • Network restricted environment – use protocol buffers binary serialization message, which is always less than the equivalent JSON message, and requires less network bandwidth than JSON

Scenarios where grpc is not recommended:

  • Browser accessible API – the browser does not fully support grpc. Although grpc web can provide browser support, it has limitations and introduces server proxy
  • Broadcast real time communication – grpc supports real-time communication over streams, but there is no concept of broadcasting messages to registered connections
  • Interprocess communication – the process must host http / 2 to accept incoming grpc calls. For windows, interprocess communication pipeline is a faster method.

From Microsoft official documents

The supported languages are as follows:

2、 Grpc on. Net core

Grpc can be used in. Net core and asp.net core very simply now. The open source address of the implementation on. Net core is https://github.com/grpc/grpc-dotnet. It is currently maintained by the official asp.net project personnel of Microsoft, with good access to the. Net core ecosystem.

The grpc functions of. Net core are as follows:

  • Grpc.aspnetcore is a framework for hosting grpc services in asp.net core, integrating grpc and asp.net core functions, such as logging, dependency injection, authentication and authorization.
  • Grpc. Net. Client grpc client based on httpclient (httpclient now supports HTTP / 2)
  • Grpc.net.clientfactory integrated with grpc clientHttpClientFactory, allows centralized configuration of grpc clients and injection into applications using di

3、 Create grpc service with asp.net core

With the templates provided by visual studio 2019 (16.3.0), you can quickly create grpc services.

To pick up what the default source code contains.

① Profileappsettings.json, more kestrel enables http / 2 configuration, because grpc is based on HTTP / 2 to communicate

② Pb protocol filegreet.protoC ා class for automatically generating services, clients and messages (representing passed data)

③ Service classGreeterService, service class integratedGreeter.GreeterBaseFrom the automatically generated classes according to the proto fileobj\Debug\netcoreapp3.0Directory

Auto generated classes:

Startup.csClass to add grpc service to endpoint routing

⑤ Csproj project file, including proto file reference

2. operation

The first run will prompt whether to trust the certificate. Click “yes”

This is because http / 2 requires HTTPS. Although the HTTP / 2 protocol does not explicitly stipulate that HTTPS is needed, HTTPS is required in the browser implementation for security. So now http / 2 and HTTPS are basically a pair.

4、 Create grpc client

1. Add a. Net core console application

2. Add package through nuget: grpc.net.client, google.protobuf, grpc.tools

3. copy the proto file of the service to the client

4. Edit the client project file and add the description of proto file

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

Be carefulGrpcServices="Client"Client and service are different here

5. Generating client projects can generate classes through proto files

6. Add client calling 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 = "Xiaochen"});
 Console. Writeline ("greeter service returns data:" + reply. Message);

7. Start the service first, and then run the client

As you can see here, the client successfully invokes the service and receives the returned message.

5、 Write a service yourself

The greeter service we used earlier was created automatically by the template. Now let’s write a service ourselves.

1. Define proto fileLuCat.proto, and add a description to the csproj project file

syntax = "proto3";

option csharp_namespace = "AspNetCoregRpcService";

import "google/protobuf/empty.proto";
Package lucat; // define package name

//Define services
service LuCat{
 //Define cat suction method
 rpc SuckingCat(google.protobuf.Empty) returns(SuckingCatResult);

message SuckingCatResult{
 string message=1;

2. Service realizationLuCatService.cs

public class LuCatService:LuCat.LuCatBase
 Private static readonly list < string > cats = new list < string > () {"English short silver gradient", "English short gold gradient", "American short", "blue cat", "civet", "orange cat"};
 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 = $"you sucked a {cats [Rand. Next (0, cats. Count)]}"

3. inStartupRegistered in endpoint route


4. Add client call

var catClient = new LuCat.LuCatClient(channel);
var catReply = await catClient.SuckingCatAsync(new Empty());
Console. Writeline ("call the call service:" + catreply. Message);

5. Operation test

6、 Practical skills

Tip 1

In the above operation steps, we need to copy proto between the service and the client, which can be omitted.

1. Copy the PROTOS folder to the solution root directory (where the SLN file is located)

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

3. Add the description of proto file in the client project file csproj

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

4. Add the description of 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. In this way, both projects use a proto file, which can be maintained only

Tip 2

There must be multiple proto files when we use them in actual projects. Do we have to update csproj files every time we add a proto file?

We can use the MSBuild variable to help us complete, we will introduce the proto file information into 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)" />


Seven. Conclusion

Grpc is now 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, we believe that it can make it easier to build. Net core microservices and better connect. Net core to grpc ecology. This is one of the most exciting features of. Net core 3.0.

reference material:

Proto 3 documentation

Creating grpc clients and services in asp.net core

Demo address

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.