Learn how to use gRPC, a language-agnostic, high-performance RPC framework, to build lightweight, high-performance services in ASP.NET Core 3.0 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. Launch the Visual Studio IDE. Click on “Create new project”. In the “Create new project” window, select “gRPC Service” from the list of templates displayed. Click Next. In the “Configure your new project” window, specify the name and location for the new project. Click Create. 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 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. 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. Launch the Visual Studio 2019 IDE. Click on “Create new project.” In the “Create new project” window, select “Console App (.NET Core)” from the list of templates displayed. Click Next. In the “Configure your new project” window shown next, specify the name and location for the new project. 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. 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: How to redirect a request in ASP.NET Core How to use attribute routing in ASP.NET Core How to pass parameters to action methods in ASP.NET Core MVC How to use API Analyzers in ASP.NET Core How to use route data tokens in ASP.NET Core How to use API versioning in ASP.NET Core How to use Data Transfer Objects in ASP.NET Core 3.1 How to handle 404 errors in ASP.NET Core MVC How to use dependency injection in action filters in ASP.NET Core 3.1 How to use the options pattern in ASP.NET Core How to use endpoint routing in ASP.NET Core 3.0 MVC How to export data to Excel in ASP.NET Core 3.0 How to use LoggerMessage in ASP.NET Core 3.0 How to send emails in ASP.NET Core How to log data to SQL Server in ASP.NET Core How to schedule jobs using Quartz.NET in ASP.NET Core How to return data from ASP.NET Core Web API How to format response data in ASP.NET Core How to consume an ASP.NET Core Web API using RestSharp How to perform async operations using Dapper How to use feature flags in ASP.NET Core How to use the FromServices attribute in ASP.NET Core How to work with cookies in ASP.NET Core How to work with static files in ASP.NET Core How to use URL Rewriting Middleware in ASP.NET Core How to implement rate limiting in ASP.NET Core How to use Azure Application Insights in ASP.NET Core Using advanced NLog features in ASP.NET Core How to handle errors in ASP.NET Web API How to implement global exception handling in ASP.NET Core MVC How to handle null values in ASP.NET Core MVC Advanced versioning in ASP.NET Core Web API How to work with worker services in ASP.NET Core How to use the Data Protection API in ASP.NET Core How to use conditional middleware in ASP.NET Core How to work with session state in ASP.NET Core How to write efficient controllers in ASP.NET Core Related content feature 14 great preprocessors for developers who love to code Sometimes it seems like the rules of programming are designed to make coding a chore. Here are 14 ways preprocessors can help make software development fun again. By Peter Wayner Nov 18, 2024 10 mins Development Tools Software Development feature Designing the APIs that accidentally power businesses Well-designed APIs, even those often-neglected internal APIs, make developers more productive and businesses more agile. By Jean Yang Nov 18, 2024 6 mins APIs Software Development news Spin 3.0 supports polyglot development using Wasm components Fermyon’s open source framework for building server-side WebAssembly apps allows developers to compose apps from components created with different languages. By Paul Krill Nov 18, 2024 2 mins Microservices Serverless Computing Development Libraries and Frameworks news Go language evolving for future hardware, AI workloads The Go team is working to adapt Go to large multicore systems, the latest hardware instructions, and the needs of developers of large-scale AI systems. By Paul Krill Nov 15, 2024 3 mins Google Go Generative AI Programming Languages Resources Videos