joydip_kanjilal
Contributor

How to build gRPC applications in ASP.NET Core

how-to
Aug 31, 202010 mins
C#Microsoft .NETSoftware Development

Learn how to use gRPC, a language-agnostic, high-performance RPC framework, to build lightweight, high-performance services in ASP.NET Core 3.0

network 5 100848391
Credit: LogRythm

gRPC is a Google-created, open source, schema-first remote procedure call (RPC) framework that takes advantage of HTTP/2 protocol to transport binary messages. These messages are serialized and deserialized using Protocol Buffers, a binary serialization protocol also from Google. gRPC takes advantage of Protocol Buffers as its Interface Definition Language (IDL).

This article presents an overview of gRPC and how we can work with it in ASP.NET Core. In this article we’ll introduce gRPC, discuss why we need it, and implement both a gRPC server and a gRPC client. 

Also on InfoWorld: Black developers tell how the US tech industry could do better ]

What is gRPC? 

Initially designed by Google, gRPC has become extremely popular for building distributed systems. gRPC supports several programming languages including C#, C++, Java, Objective-C, Python, Ruby, Go, and Node.js — and the list is growing. Support for gRPC was introduced in .NET Core 3.0, which makes gRPC a first-class citizen in the .NET Core ecosystem.

gRPC provides the following benefits:

  • High performance
  • Light weight
  • Support for bi-directional streaming
  • Support for binary serialization using Protocol Buffers
  • Support for language agnostic implementations

gRPC communication patterns

gRPC supports the following communication patterns.

  • Unary RPC: The client sends a single request and the server sends back a single response.
  • Server streaming RPC: The client sends a single request and the server sends back a stream of responses. 
  • Client streaming RPC: The client sends a stream of messages to the server and the server sends back a single response.
  • Bi-directional streaming RPC: The client sends a stream of messages to the server and the server sends back a stream of responses.

Now let’s get started. To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here.

Create a gRPC project in Visual Studio

First off, let’s create a gRPC project in Visual Studio. ASP.NET Core 3.0 (and later) ships with a gRPC template that you can take advantage of to build gRPC services. Assuming Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new gRPC Service project in Visual Studio.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project”.
  3. In the “Create new project” window, select “gRPC Service” from the list of templates displayed.
  4. Click Next. 
  5. In the “Configure your new project” window, specify the name and location for the new project.
  6. Click Create.
  7. In the “Create a new gRPC Service” window, click Create. 

This will create a new gRPC service project in Visual Studio. If you observe the list of packages in the Solution Explorer of your new gRPC project, you should see the Grpc.AspNetCore package listed there. When you expand Grpc.AspNetCore, you should see the following three packages:

  • Google.Protobuf
  • Grpc.AspNetCore.Server.ClientFactory
  • Grpc.Tools
grpc aspnet core packages IDG

Your gRPC service project should include the Google.Protobuf, Grpc.AspNetCore.Server.ClientFactory, and Grpc.Tools packages. 

Further, two solution folders will be created by default – one named Protos, which will contain the .proto files, and the other named Services, which will contain your concrete, strongly-typed service classes.

grpc aspnet core solution folders IDG

Your gRPC service project should also include two solution folders, named Protos and Services. Protos stores .proto files used to define contracts and messages. Services stores strongly typed service classes. 

Note that a gRPC service consists of a code file that implements the service and a .proto file that describes the service. gRPC takes advantage of .proto files to define services and message contracts. The Protos folder is where you will have all your message contracts.

gRPC .proto file example in ASP.NET Core

The name of the default gRPC service created with your project is GreeterService, and it is stored inside the Services folder. The default .proto file created for you with the gRPC project looks like this:

syntax = "proto3";
option csharp_namespace = "gRPCDemo";
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;
}

In the preceding code snippet, Greeter is the name of the service and HelloReply and HelloRequest are the message contracts – also known as POCO classes in C# jargon. SayHello accepts HelloRequest as a request message and returns HelloReply as the response message.

Here is another example of a .proto file. Note the use of AuthorRequest and AuthorResponse message contracts.

syntax = "proto3";
service AuthorService {
  rpc GetAuthor (AuthorRequest) returns (AuthorResponse);
}
message AuthorRequest {
  string author_id = 1;
}
message AuthorResponse) {
  string first_name = 1;
  string last_name = 2;
}

gRPC service example in ASP.NET Core

The default Greeter service generated by Visual Studio looks like this. For the sake of simplicity, let’s use this service as the server in our example.

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
            });
        }
    }

In the preceding code example, the GreeterService class extends the Greeter.GreeterBase class, where Greeter is the name of the service (mentioned in the greet.proto file) and GreeterBase is the name of the class generated when creating C# stubs.

Configure gRPC in ASP.NET Core

You can enable gRPC support for your ASP.NET Core web application by calling the AddGrpc() method in the ConfigureServices method as shown below.

public void ConfigureServices(IServiceCollection services)
    {
        services.AddGrpc();
    }

To add a gRPC service to the routing pipeline, you should call the MapGrpcService() method as shown below.

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGrpcService<GreeterService>();
                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Hello World!");
                });
            });
        }

Create a gRPC client in ASP.NET Core

Now that the gRPC service has been created, the next thing you need to do is implement a gRPC client to consume the service. While there are no templates available to create a gRPC client, you can take advantage of a .NET Core console application to build a gRPC client. Follow the steps outlined below to create a new .NET Core console application project in Visual Studio 2019.

  1. Launch the Visual Studio 2019 IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “Console App (.NET Core)” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window shown next, specify the name and location for the new project.
  6. Click Create.

This will create a new .NET Core console application project in Visual Studio 2019. We’ll use this project to build a gRPC client.

First we’ll need to install the following NuGet packages in the gRPC client application. These packages will enable the client to connect to the server application we created earlier.

  • Grpc.Tools – contains the necessary types that can be used to provide tooling support for protobuf files
  • Grpc.Net.Client – contains the .NET Core client that can be used to establish a connection channel and send messages to a particular endpoint 
  • Google.Protobuf – contains the protobuf APIs that can be leveraged for writing protobuf files

Install the Grpc.Tools, Grpc.Net.Client, and Google.Protobuf NuGet packages via the NuGet Package Manager or execute the following commands in the NuGet Package Manager Console of the console application project you just created.

Install-Package Grpc.Net.Client
Install-Package Google.Protobuf
Install-Package Grpc.Tools

Once these NuGet packages have been installed, you should copy the .proto files residing at the server to the client application.

Open the .proj file of the client application and insert the following line inside the tag.

<Protobuf Include="Protosgreet.proto" GrpcServices="Client" />

The following code snippet illustrates how you can connect to the gRPC service from the client application.

static async System.Threading.Tasks.Task Main(string[] args)
{
  using var grpcChannel = GrpcChannel.ForAddress("https://localhost:5001");
  var grpcClient = new Greeter.GreeterClient(grpcChannel);
  var reply = await grpcClient.SayHelloAsync
  (new HelloRequest { Name = "Joydip" });
  Console.WriteLine(reply.Message);
  Console.ReadKey();
}

Now, first execute the server application and then the client. The output for the server (left) and client (right) should appear as shown in the image below.

grpc aspnet core output IDG

Output from our demo gRPC server application (left) and gRPC client (right). 

Two of the biggest benefits of gRPC are its support for bidirectional streaming over HTTP/2 and its binary message format for information exchange. You can take advantage of gRPC to build microservices-based applications, native mobile applications, and Internet of Things (IoT) applications. 

And building a gRPC service is easy. You don’t have to define controllers on the server side (like you do for a RESTful service) or build HTTP requests on the client side to consume the services. We’ll explore working with gRPC in more depth in future posts here.

How to do more in ASP.NET Core:

joydip_kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author