Introduction To gRPC And its Implementation In .NET Core 3.1


gRPC is an open source remote procedure call system developed at Google in 2015. It uses HTTP/2 to transport binary messages and by default protocol buffers as Interface Definition language (IDL) for describing service interface and the structure of messages. 
  1. // The greeter service definition.  
  2.  service Greeter {  
  3.    // Sends a greeting  
  4.    rpc SayHello (HelloRequest) returns (HelloReply) {}  
  5.  }  
  6.  // The request message containing the user's name.  
  7.  message HelloRequest {  
  8.    string name = 1;  
  9.  }  
  10.  // The response message containing the greetings  
  11.  message HelloReply {  
  12.    string message = 1;  
  13.  }  
gRPC defines four types of service methods,
  1. Unary RPCs where client send a single request to the server and get a single response back.
  2. Server streaming RPCs where client sends request to the server and gets a stream to read a sequence of messages back.
  3. Client Streaming RPCs where client writes a sequence of messages and sends them to the server, again using a provided stream.
  4. Bidirectional Streaming RPCs where both sides send a sequence of messages using read-write stream.
If we compare gRPC to Web API , following are the differences,
  1. Web API is based on REST architecture where as gRPC proposes RPC model , a model where as client invokes remote procedure on the server.
  2. Web API uses HTTP for transport whereas gRPC uses HTTP/2.
  3. Data exchanged by Web API is human readable format(typically JSON), while gRPC uses compact binary format.
Before creating gRPC Services make sure .NET Core 3.1 SDK is installed on your local, this can be checked by typing command : 'dotnet --version' in console window. If it's not installed, download Download .NET Core 3.1 (Linux, macOS, and Windows) ( and install on your machine.

Creating a gRPC Service

The application we are going to build is a microservice that calculates a discount based on the  type of customer -- gold or platinum or silver -- which can be further extended. Start by creating a new folder, grpc-dotnet-microservice,  and adding both client and service applications.
Navigate to this folder and create the server project by typing the following command in the console window,
The above command creates a new sample .NET Core gRPC project in folder created CalculateDiscountService.

Defining the Contract

The first step is to define the contract which is an interface that tell you the  functionality or functions exposed by the service. In gRPC framework this interface is defined through Protocol buffer or protobuf. In particular this interface is defined in .proto file.
So move to ~\CalculateDiscountService\Protos folder , rename the default proto file to discount-calculate-service.proto file and do the following changes.
  1. syntax = "proto3";  
  3.  option csharp_namespace = "CalculateDiscountService";  
  4.  package CalculateDiscount;  
  6.  service CalculateDiscountAmount {  
  7.    rpc AmountCalculate (CalculateRequest) returns (CalculateReply);  
  8.  }  
  10.  message CalculateRequest {  
  11.    string customertype = 1;  
  12.  }  
  14.  message CalculateReply {  
  15.    double customerdiscount = 1;  
  16.  }  
Let's understand line by line. The first two rows tell the syntax of proto buff version in use and C# namespace. The next line tells package name in this case = CalculateDiscount 
Next block of code is similar in C# as follows,
  1. class CalculateDiscountAmount {  
  2.    public abstract CalculateReply AmountCalculate(CalculateRequest calculateRequest);  
  3. }  
Here CalculateReply is return type, CalculateRequest is input parameter, AmountCalculate is an abstract function and CalculateDiscountAmount is C# class. In proto file the CalculateRequest and CalculateReply messages' unique number is assigned in fields defined inside, this orders the order of data when serialization and deserialization is done by protocol buffer.
Once the contract is defined, you need to make sure the application is aware of the new proto file. Update the CalculateDiscountService.csproj file, below, 
  1. <Project Sdk="Microsoft.NET.Sdk.Web">     
  2.    <PropertyGroup>  
  3.       <TargetFramework>netcoreapp3.1</TargetFramework>  
  4.    </PropertyGroup>  
  5.    <ItemGroup>  
  6.       <Protobuf Include="Protos\discount-calculate-service.proto" GrpcServices="Server" />   </ItemGroup>  
  7.    <ItemGroup>  
  8.       <PackageReference Include="Grpc.AspNetCore" Version="2.27.0" />  
  9.    </ItemGroup>  
  10. </Project>  
Here .proto file name is specified along with GrpcServices attribute set to 'Server'.

Service Implementation

Navigate to services folder, rename the GreeterService.cs file to CalculateDiscountService.cs and replace the contents with below, 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using Grpc.Core;  
  6. using Microsoft.Extensions.Logging;  
  8. namespace CalculateDiscountService  
  9. {  
  10.     public class CalculateDiscountAmountService : CalculateDiscountAmount.CalculateDiscountAmountBase  
  11.     {  
  12.         private readonly ILogger<CalculateDiscountAmountService> _logger;  
  13.         public CalculateDiscountAmountService(ILogger<CalculateDiscountAmountService> logger)  
  14.         {  
  15.             _logger = logger;  
  16.         }  
  18.         public override Task<CalculateReply> AmountCalculate(CalculateRequest request, ServerCallContext context)  
  19.         {  
  21.             return Task.FromResult(new CalculateReply  
  22.             {  
  23.                 Customerdiscount=ReturnDiscount(request.Customertype)  
  24.             });  
  27.         }   
  28.         private double ReturnDiscount(string customertype)  
  29.         {  
  30.             double discount=0.0;  
  32.             if (customertype=="GOLD")  
  33.             {  
  34.                 discount=15.6;   
  35.             }  
  36.             else if (customertype=="PLATINUM")  
  37.             {  
  38.                 discount=20.6;  
  39.             }  
  40.             else if (customertype=="DIAMOND")  
  41.             {  
  42.                 discount=25.6;  
  43.             }  
  45.             return discount;  
  47.         }  
  51.     }  
  52. }  
Here we are implementing the CalculateDiscountAmountService class which inherits from CalculateDiscountAmount.CalculateDiscountAmountBase class. This base class is generated from data contained in .proto file ( discount-calculate-service.proto ) at build time.
It contains AmountCalculate function which is implementation of rpc definition in .proto file and CalculateReply and CalculateRequest types as return type and request parameter defined as message types. Also update Startup.cs file to map CalculateDiscountAmountService class as gRPC service, below,
Now navigate to root folder of project, run the project by typing command in command prompt 'dotnet run',
The above command will start the gRPC service. Now to interact with this service we will be creating a console client application.

Creating a gRPC Client

Navigate to folder `\grpc-dotnet-microservice and create a new project by typing the following command in cmd,
The above command will create a console application in folder created DiscountCalculateClient. Now move to this folder and add the required dependencies by typing the below commands,
  1. dotnet add DiscountCalculateClient.csproj package Grpc.Net.Client  
  2. dotnet add DiscountCalculateClient.csproj package Google.Protobuf  
  3. dotnet add DiscountCalculateClient.csproj package Grpc.Tools  
Grpc.Net.Client library for .NET core client, Google.Protobuf - C# runtime library for managing protocol buffers and Grpc.Tools - complier that converts proto files into C# code.
Now client application needs to be aware of details about how to invoke server application, what parameters to pass and what will be the possible return type.
This is done by adding the already defined proto file. First create a proto folder inside DiscountCalculateClient and copy the discount-calculate-service.proto from gRPC service and update the DiscountCalculateClient.csproj project file by adding the reference of .proto file. 
  1. <Project Sdk="Microsoft.NET.Sdk">  
  3.   <PropertyGroup>  
  4.     <OutputType>Exe</OutputType>  
  5.     <TargetFramework>netcoreapp3.1</TargetFramework>  
  6.   </PropertyGroup>  
  8.   <ItemGroup>  
  9.     <PackageReference Include="Google.Protobuf" Version="3.14.0" />  
  10.     <PackageReference Include="Grpc.Net.Client" Version="2.33.1" />  
  11.     <PackageReference Include="Grpc.Tools" Version="2.34.0">  
  12.       <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>  
  13.       <PrivateAssets>all</PrivateAssets>  
  14.     </PackageReference>  
  15.   </ItemGroup>  
  17.   <ItemGroup>  
  18.   <Protobuf Include="Protos\discount-calculate-service.proto" GrpcServices="Client" />  
  19.   </ItemGroup>  
  21. </Project>  
Note here Protobuf element has GrpcServices attribute set to client. Now to call gRPC service from client , edit the Program.cs file,
  1. using System;  
  2. using CalculateDiscountService;  
  3. using Grpc.Net.Client;  
  4. using System.Net.Http;  
  5. namespace DiscountCalculateClient  
  6. {  
  7.     class Program  
  8.     {  
  9.         static void Main(string[] args)  
  10.         {  
  11.             var httpHandler = new HttpClientHandler();  
  13.             httpHandler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;  
  15.             string customerType="GOLD";  
  16.             var channel=GrpcChannel.ForAddress("https://localhost:5001",new GrpcChannelOptions { HttpHandler = httpHandler });  
  17.             var client=new CalculateDiscountAmount.CalculateDiscountAmountClient(channel);  
  18.             var request=new CalculateRequest{Customertype=customerType};  
  19.             var reply=  client.AmountCalculate(request);  
  21.             Console.WriteLine($"Discount for customer type {customerType}  is {( reply.Customerdiscount)}");  
  22.             Console.WriteLine("Press any key to exit...");  
  23.             Console.ReadKey();  
  25.         }  
  26.     }  
  27. }  
Here we are creating a channel which points to the address where the service is running along with adding the required configuration to ignore invalid certificate or certificate is not installed and next passed as constructor to gRPC client CalculateDiscountAmountClient class. Finally its function is called by passing required parameter.
Below is the output in client application after launching through command: 'dotnet run',
Some of the new features introduced in .NET 5 for gRPC,
  1. It is supported on browser with gRPC-Web which makes its compatible with browser API.
  2. It can be hosted on HTTP.sys and IIS on Windows with supported version of Windows installed.


In this article we discussed about gRPC, its implementation in .NET core 3.1 and new features introduced in .NET 5