C# Quick Start

This guide gets you started with gRPC in C# with a simple working example.

Note

This is a quick start guide for the gRPC C# implementation based on Core native library. See gRPC for .NET Quick Start for how to start with the “grpc-dotnet” implementation.

Prerequisites

Whether you’re using Windows, OS X, or Linux, you can follow thisexample by using either an IDE and its build tools,or by using the the .NET Core SDK command line tools.

First, make sure you have installed thegRPC C# prerequisites.You will also need Git to download the sample code.

Download the example

You’ll need a local copy of the example code to work through this quick start.Download the example code from our GitHub repository (the following commandclones the entire repository, but you just need the examples for this quick startand other tutorials):

  1. # Clone the repository to get the example code:
  2. $ git clone -b v1.28.1 https://github.com/grpc/grpc
  3. $ cd grpc

This document will walk you through the “Hello World” example.The projects and source files can be found in the examples/csharp/Helloworld directory.

The example in this walkthrough already adds the necessarydependencies for you (Grpc, Grpc.Tools and Google.Protobuf NuGet packages).

Build the example

Using Visual Studio (or Visual Studio for Mac)

  • Open the solution Greeter.sln with Visual Studio
  • Build the solution

Using .NET Core SDK from the command line

From the examples/csharp/Helloworld directory:

  1. > dotnet build Greeter.sln

Note

If you want to use gRPC C# from a project that uses the “classic” .csproj files (supported by Visual Studio 2013, 2015 and older versions of Mono), please refer to theGreeter using “classic” .csproj example.

Run a gRPC application

From the examples/csharp/Helloworld directory:

  • Run the server:
  1. > cd GreeterServer
  2. > dotnet run -f netcoreapp2.1
  • From another terminal, run the client:
  1. > cd GreeterClient
  2. > dotnet run -f netcoreapp2.1

Congratulations! You’ve just run a client-server application with gRPC.

Update a gRPC service

Now let’s look at how to update the application with an extra method on theserver for the client to call. Our gRPC service is defined using protocolbuffers; you can find out lots more about how to define a service in a .protofile ingRPC Basics: C#. For now all you need to know is that both theserver and the client “stub” have a SayHello RPC method that takes aHelloRequest parameter from the client and returns a HelloResponse from theserver, and that this method is defined like this:

  1. // The greeting 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. }

Let’s update this so that the Greeter service has two methods. Editexamples/protos/helloworld.proto and update it with a new SayHelloAgainmethod, with the same request and response types:

  1. // The greeting service definition.
  2. service Greeter {
  3. // Sends a greeting
  4. rpc SayHello (HelloRequest) returns (HelloReply) {}
  5. // Sends another greeting
  6. rpc SayHelloAgain (HelloRequest) returns (HelloReply) {}
  7. }
  8. // The request message containing the user's name.
  9. message HelloRequest {
  10. string name = 1;
  11. }
  12. // The response message containing the greetings
  13. message HelloReply {
  14. string message = 1;
  15. }

Remember to save the file!

Generate gRPC code

Next we need to update the gRPC code used by our application to use the new service definition.

The Grpc.Tools NuGet package contains the protoc and protobuf C# plugin binaries neededto generate the code. Starting from version 1.17 the package also integrates withMSBuild to provideautomatic C# code generationfrom .proto files.

This example project already depends on the Grpc.Tools.1.28.1 NuGet package so just re-building the solutionis enough to regenerate the code from our modified .proto file.

You can rebuild just like we first built the originalexample by running dotnet build Greeter.sln or by clicking “Build” in Visual Studio.

The build regenerates the following filesunder the Greeter/obj/Debug/TARGET_FRAMEWORK directory:

  • Helloworld.cs contains all the protocol buffer code to populate,serialize, and retrieve our request and response message types
  • HelloworldGrpc.cs provides generated client and server classes,including:
    • an abstract class Greeter.GreeterBase to inherit from when definingGreeter service implementations
    • a class Greeter.GreeterClient that can be used to access remote Greeterinstances

Update and run the application

We now have new generated server and client code, but we still need to implementand call the new method in the human-written parts of our example application.

Update the server

With the Greeter.sln open in your IDE, open GreeterServer/Program.cs.Implement the new method by editing the GreeterImpl class like this:

  1. class GreeterImpl : Greeter.GreeterBase
  2. {
  3. // Server side handler of the SayHello RPC
  4. public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
  5. {
  6. return Task.FromResult(new HelloReply { Message = "Hello " + request.Name });
  7. }
  8. // Server side handler for the SayHelloAgain RPC
  9. public override Task<HelloReply> SayHelloAgain(HelloRequest request, ServerCallContext context)
  10. {
  11. return Task.FromResult(new HelloReply { Message = "Hello again " + request.Name });
  12. }
  13. }

Update the client

With the same Greeter.sln open in your IDE, open GreeterClient/Program.cs.Call the new method like this:

  1. public static void Main(string[] args)
  2. {
  3. Channel channel = new Channel("127.0.0.1:50051", ChannelCredentials.Insecure);
  4. var client = new Greeter.GreeterClient(channel);
  5. String user = "you";
  6. var reply = client.SayHello(new HelloRequest { Name = user });
  7. Console.WriteLine("Greeting: " + reply.Message);
  8. var secondReply = client.SayHelloAgain(new HelloRequest { Name = user });
  9. Console.WriteLine("Greeting: " + secondReply.Message);
  10. channel.ShutdownAsync().Wait();
  11. Console.WriteLine("Press any key to exit...");
  12. Console.ReadKey();
  13. }

Rebuild the modified example

Rebuild the newly modified example just like we first built the originalexample by running dotnet build Greeter.sln or by clicking “Build” in Visual Studio.

Run!

Just like we did before, from the examples/csharp/Helloworld directory:

  • Run the server:
  1. > cd GreeterServer
  2. > dotnet run -f netcoreapp2.1
  • From another terminal, run the client:
  1. > cd GreeterClient
  2. > dotnet run -f netcoreapp2.1

What’s next