Click here to Skip to main content
15,886,689 members
Articles / Programming Languages / C#

Getting Started with gRPC Client and Server using ASP.NET Core

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
15 Aug 2019CPOL8 min read 17.6K   317   8   2
In this article, we will see how to create a gRPC service using the ASP.NET Core template. We will also create a client application using .NET Console core to call the gRPC service server method directly to send and receive the message from the client application.

Introduction

Image 1

In this article, we will see how to create a gRPC service using the ASP.NET Core template. We will also create a client application using .NET Console core to call the gRPC service server method directly to send and receive the message from the client application.

gRPC

gRPC is a fast, efficient and lightweight Remote Procedure Call which is widely used in microservices. gRPC was initially developed by Google and now it’s open source.

In ASP.NET Core3, we can see that a new template has been included as gRPC Service. Yes, using this template, we can create our gRPC Service and create a client application as .NET Core Console, WinForms or ASP.NET Core for data serialization for sending and receiving data from client to server. gRPC uses HTTP/2 for the transport. gRPC uses protocol buffer aka Protobuf as the data serialization format which is used to send and receive from the client to the server.

Protobuf File

gRPC uses protobuf as the default data serialization to send and receive data from the client and server. In other words, the protobuf is used as the Interface Design Language. In order to work with gRPC service, we need to understand the protobuf file as well. Protobuf files have 2 parts as one is for defining the gRPC Service and the other part is to define the message sent between the client to the server. Here, we will see each section of the protobuf file.

In the first line of the protobuf file, we need to declare the syntax and this syntax is to mention the version we are using of protocol buffer language and here in our example, we are using the proto3.

C#
syntax = "proto3";

Next, we give our C# application namespace name that is our solution name.

C#
option csharp_namespace = "GrpcGreeter";

Next is the service part and here, we have created the service named as the Greeter. When we create the gRPC service application, the proto file has been added by default and this below service has been created automatically.

In this Greeter Service, we have created 2 calls as SayHello and Servermessage in this call, each call sends HelloRequest as message and receives the HelloReplay message.

C#
// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
  rpc Servermessage (HelloRequest) returns (HelloReply) {}
}

Reference link: https://docs.microsoft.com/en-us/aspnet/core/grpc/?view=aspnetcore-3.0

Background

Make sure you have installed all the prerequisites on your computer. If not, then download and install them all, one by one.

Prerequisites

Using the Code

Step 1 - Create a gRPC Service Application

After installing all the prerequisites listed above, click Start >> Programs >> Visual Studio 2019 >> Visual Studio 2019 on your desktop. >> Click New Project.

Image 2

Click on ASP.NET Core Web Application and click "Next".

Image 3

Enter your project name and click the "Create" button.

Image 4

Now, we can see that for ASP.NET Core 3.0 has been listed. We select the gRPC Service and click create to create our gRPC service application.

Image 5

gRPC Project Structure

Image 6

Once we created the gRPC Service project, we can see as by default the project will contain the Protos folder with protobuf file as extension with “.proto” file. Also, we can see the Services folder with our Service class file. In this article beginning, we have seen in detail about what is a protobuf file and what the protobuf file contains. In our gRPC Service project, we can see the proto file has been by default created with sayHello method call to send and receive the request and replay between client and the server.

Image 7

We add one more method call:

rpc Servermessage (HelloRequest) returns (HelloReply) {}

Here, we are adding one more method call for our example and let’s see how to use this in our service and client application as well. Here is the complete code of greet.proto file.

C#
syntax = "proto3";

option csharp_namespace = "shanugRPC";

package Greet;

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
   rpc Servermessage (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;
}

The service folder has a service class as default with GreeterService. This class has SayHello method which was created by default. Same like this, we can add our own method to send response to the .

Image 8

Now we also need to add one more Override method as ServerMessage and from this service, we can send method message return to client application. Like this, you can create any number of methods and call them from the client application for message request and reply from the server.

Here is the complete code of our Service.

C#
public class GreeterService : Greeter.GreeterBase
  {
      public override Task<HelloReply>
             SayHello(HelloRequest request, ServerCallContext context)
      {
          return Task.FromResult(new HelloReply
          {
              Message = "Hello " + request.Name
          });
      }

      public override Task<HelloReply>
             Servermessage(HelloRequest request, ServerCallContext context)
      {
          return Task.FromResult(new HelloReply
          {
              Message = "Your Friend Name is :   " + request.Name
          });
      }
  }

appsetting.json file will contain the protocols used for the service. Here, we can see Http2 protocol has been used for the gRPC service.

Image 9

Build and Run the Application

When we build and run the application, we can see as the service is running successfully and also we can see our gRPC service is listening on http://localhost:50051.

Image 10

Note that as gRPC is template is configured to use the TSL and the clients need to use the HTTPS to call the server. But here, we are using the http in order to use the http in our client application, we need to use this below code to connect between server and client

C#
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);

We will see this in detail while creating the client application.

Step 2: Creating Client Console .NET Core Application

After installing all the prerequisites listed above, click Start >> Programs >> Visual Studio 2019 >> Visual Studio 2019 on your desktop. >> Click New Project.

Image 11

Click on Console App (.NET Core) and click "Next".

Image 12

Enter your project name and click the "Create" button.

Image 13

Now our console application has been created.

Add the Required Packages

In order to send and receive message between client and the gRPC Service, we need to add Grpc.Net.Client, Google.Protobuf and Grpc.Tools packages to our project.

Grpc.Net.Client packages is used for the .NET Core client, Google.Protobuf packages contain the protobuf message APIs to be used for the C# language. Grpc.Tool contains the tooling support for the protobuf files.

We can install this package by NuGet Package Manager or by Manage NuGet Packages.

Installing the Packages by Manage NuGet Packages

Right click your gRPC client project and click on Manage NuGet Packages.

Image 14

Select Browse tab, enter “Grpc.net.Client” search and Install the package to our client project.

Image 15

Same like that, install the “Google.Protobuf” search and Install the package to our client project.

Image 16

Same like that, install the “Grpc.Tools” search and Install the package to our client project.

Image 17

Adding Protobuf File to Client Application

In our client application, we need to add the same protobuf file for data send and receive from the client to server. First, we create the Protos folder in our client project.

Image 18

Now we need to add the protobuf which we used in Service project to the Protos folder.

Right click the Protos folder and click on Add Existing Item.

Image 19

Select and add the greet.proto file which we used in our Service project .

Image 20

Now in order to use the greet.proto file in our project, we need to add the itemGroup with Protobuf to our project.

Right click our Project and click Edit Project File.

Image 21

Add the below code to the project file:

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

Build the application in order to use our Service in client application.

Working with Client Program.cs File

Now it's time for us to create the client program to send and receive the message from client to our gRPC Service.

For this, we open the program.cs file and add the below namespace. Here shanugRPC is our service project namespace.

C#
using shanugRPC ;
using Grpc.Net.Client;
using Grpc.Core;

Now add the below code in the Main method of yourprogram.cs file:

C#
static async Task Main(string[] args)
      {
          var httpClient = new HttpClient();
          httpClient.BaseAddress = new Uri("https://localhost:50051");
          var client = GrpcClient.Create<Greeter.GreeterClient>(httpClient);

          var reply = await client.SayHelloAsync(
                    new HelloRequest { Name = "GreeterClient" });
          Console.WriteLine("Greeting: " + reply.Message);
          Console.WriteLine("Press any key to exit...");
          Console.ReadKey();
      }

Build and Run the Application

Note: first run our Service application and then run our client application for the client and server communication. Always make sure as service is running before running the client.

When we run the application, we might get the error as

Image 22

This means here our Service listening to http://localhost:50051 but the above code will be work for https and in our example, we need to use the https://localhost:50051, so we change the code like below:

C#
static async Task Main(string[] args)
        {
            //----------------
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport",
                                  true);
            var httpClient = new HttpClient(); 
            httpClient.BaseAddress = new Uri("http://localhost:50051");
            var client = GrpcClient.Create<Greeter.GreeterClient>(httpClient);

            var reply = await client.SayHelloAsync(
                      new HelloRequest { Name = "Shanu" });
            Console.WriteLine("Greeting: " + reply.Message);
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();

        }

Code Part Explanation

For using the http instead of the https, first set the below code part:

C#
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
          var httpClient = new HttpClient();

Next, we create the client object with url:

C#
var httpClient = new HttpClient();
 httpClient.BaseAddress = new Uri("http://localhost:50051");
 var client = GrpcClient.Create<Greeter.GreeterClient>(httpClient);

Next, we send and get the replay from the service by calling the service method and pass the request and get the reply message.

C#
var reply = await client.SayHelloAsync(
          new HelloRequest { Name = "Shanu" });
Console.WriteLine("Greeting: " + reply.Message);

Run the Application

When we run the application, we can see result as we send name as Shanu to the service from the client and we get the reply from the service as “Hello Shanu”.

Now we change the code to get our name and our friend's name to send to the service for diriment method call and get their play from each message and display the results.

Here is the complete code. We have used the similar code and asked the user to enter their name and friend name and called service method SayHello and Servermessage method to send and receive message from the client and server.

C#
static async Task Main(string[] args)
      {
          ////var httpClient = new HttpClient();
          ////// The port number(5001) must match the port of the gRPC server.
          ////httpClient.BaseAddress = new Uri("https://localhost:50051");
          ////var client = GrpcClient.Create<Greeter.GreeterClient>(httpClient);

          //----------------
          AppContext.SetSwitch
          ("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
          var httpClient = new HttpClient();
          // The port number(5001) must match the port of the gRPC server.
          httpClient.BaseAddress = new Uri("http://localhost:50051");
          var client = GrpcClient.Create<Greeter.GreeterClient>(httpClient);

          //-----------------------

          Boolean isexit = true;
          while (isexit)
          {
              Console.WriteLine("Enter Your Name to send request to the server : ");
              String myName = Console.ReadLine();

              var reply = await client.SayHelloAsync(
                                new HelloRequest { Name = myName });
              Console.WriteLine("Hello world : " + reply.Message);

              Console.WriteLine("Enter YourFriend  Name  : ");
              String friendName = Console.ReadLine();

              var serverreply = await client.ServermessageAsync(
                                new HelloRequest { Name = friendName });
              Console.WriteLine("Message from Server -> " + serverreply.Message);

              Console.WriteLine("Do you want to continue say Y or N");
              string YN = Console.ReadLine();
              if (YN.ToLower() == "y")
              {
                  isexit = true;
              }
              else
              {
                  isexit = false;
              }
              Console.WriteLine("==========================  ============");
              Console.WriteLine("");
          }

          Console.WriteLine("Press any key to exit...");
          Console.ReadKey();
      }

Image 23

Points of Interest

In this article, I discussed how to work with gRPC Service and client application to send and receive message from gRPC Service. In order to work with this sample, don't forget to install .NET Core 3.0 and Visual Studio 2019 preview.

History

  • 2019-08-12: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader
India India
Microsoft MVP | Code Project MVP | CSharp Corner MVP | Author | Blogger and always happy to Share what he knows to others. MyBlog

My Interview on Microsoft TechNet Wiki Ninja Link

Comments and Discussions

 
QuestionTask & async Pin
Fabrice Avaux13-Aug-19 2:49
Fabrice Avaux13-Aug-19 2:49 
AnswerRe: Task & async Pin
syed shanu13-Aug-19 13:33
mvasyed shanu13-Aug-19 13:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.