
Implementing a C# gRPC service involves creating a service definition in a .proto file. This file defines the service's methods and data types.
To generate the service implementation in C#, you can use the gRPC tool to create a C# class that implements the service. This class will contain the methods defined in the .proto file.
The service implementation class will contain a method for each service method defined in the .proto file. For example, if you have a service method called "GetUser", the implementation class will contain a method called "GetUser".
The implementation class will also contain the necessary code to handle the service calls, such as deserializing the request and serializing the response.
See what others are reading: C Programming Web Server
Prerequisites
Before we dive into building a C# gRPC service, let's make sure we have the necessary tools in place. To get started, you'll need the .NET 6.0 SDK or later installed on your machine.
A code editor is also a must-have, and you can use either Visual Studio or VSCode to write and edit your code.
To be more specific, here are the prerequisites you'll need to meet:
- .NET 6.0 SDK or later
- A code editor such as Visual Studio or VSCode
Setting Up the Project
To set up a C# gRPC service, start by creating a new ASP.NET Core project configured for gRPC using the dotnet CLI. This will create a new project in a folder called GrpcService that’s pre-configured with gRPC dependencies.
You can then install the required gRPC NuGet packages by running the following commands in the project directory: Grpc.AspNetCore, Google.Protobuf, and Grpc.Tools. This will allow you to define gRPC services, work with Protocol Buffers, and generate code from .proto files.
Here are the required NuGet packages you need to install: Grpc.AspNetCoreGoogle.ProtobufGrpc.Tools
A unique perspective: Google Drive Api Service Account
Run
To run the project, you'll need to start the server and client. Open a terminal in the GrpcClient project folder and run the client to make a request.
You should see the following output: the client sending the request and receiving a response from the server, or the response printed in the console: Greeting: Hello World.
To start the server, navigate to the bin > Debug folder of Greeter Server and run the executable. You should see the server listening.
In a separate command prompt, navigate to the bin > Debug folder of Greeter Server and run the executable to run the Greeter Client.
Define the Service
To define a gRPC service in C#, you need to create a .proto file, which is where you specify the service methods and request/response messages. Create a folder called Protos in your project and add a .proto file for your service, let's name it greet.proto.
A .proto file is where you define your gRPC service and the messages that will be used for requests and responses. You can create a file named greet.proto inside the Protos directory and add the following content.
The service Greeter with a method SayHello, which takes a HelloRequest message containing a name and returns a HelloReply message with a greeting message, is a good starting point. This is a simple example, but you can add more methods and messages as needed.
Navigate to https://localhost:5001 in your browser after defining your service in a .proto file. You should see a page confirming that the gRPC service is successfully running, which means you have just created and run your first gRPC service using .NET.
Implementing the Service
To implement the service, create a new file called GreeterService.cs inside a Services folder. This file will extend the generated Greeter.GreeterBase class, automatically created from the greet.proto file.
The implementation of the SayHello method in GreeterService.cs is straightforward - it simply returns a greeting message when invoked. The method takes a HelloRequest message containing a name and returns a HelloReply message with a greeting message.
You can find the specific implementation details in the GreeterService.cs file, where the SayHello method is defined.
Implementing the Service
To implement the service, you'll need to create a new file called GreeterService.cs inside a Services folder. This file will extend the generated Greeter.GreeterBase class, which is automatically generated from the .proto file.
The GreeterService class will implement the SayHello method, which returns a greeting message using the name provided in the request. This implementation is straightforward, simply returning a greeting message.
Here's the implementation of the SayHello method:
This is where the actual functionality of the service is implemented. The method takes a HelloRequest message containing a name and returns a HelloReply message with a greeting message.
In this implementation, the SayHello method returns a greeting message using the name provided in the request.
On a similar theme: Access Azure Key Vault Using Service Principal C#
RpcException
Throwing an RpcException is a deliberate choice, as it's more explicit in the code than simply changing the request status to NotFound. This approach ensures that every request with a non-OK status code will result in an exception being thrown to the client.
Exceptions can also include a brief message, like in the example, and even metadata for sending supporting data to the client. A longer exception message is also possible.
The RpcException is used to send a status code, a brief message, and optional metadata.
Handling Service Calls
Handling service calls in a gRPC service is a crucial part of ensuring that requests are properly handled and responded to. This is achieved by implementing the service methods in a .proto file.
To define a service method, you create a .proto file where you specify the service methods and the request/response messages. For example, in the greet.proto file, a service called Greeter is defined with a single SayHello method that takes a HelloRequest and returns a HelloReply.

The service method implementation is where the actual logic for handling the service call is written. This is done by overriding the virtual method in the abstract ProductGrpBase type. For instance, in the ProductService class, the GetProduct method is overridden to search for a product with the ID received via parameter.
A service call can be successful or unsuccessful, and the status of the call is used to indicate the outcome. The status can be one of several values, including OK, CANCELLED, or UNKNOWN.
Here are some common reasons why an RpcException is thrown during a service call:
When a product is not found.When a product is found but is inactive.
The RpcException is thrown to provide a clear indication of the reason for the failure, allowing the client to take appropriate action.
Handling Call
Handling a gRPC call involves implementing the service logic in a way that's easy to understand and maintain. This typically involves creating a new class that inherits from the generated base class.

The ProductService class in Example 3 is a great example of this. It overrides the GetProduct method to implement the logic for handling the gRPC call.
To handle a gRPC call, you need to override the method that was generated by the gRPC compiler. This method will have a parameter that matches the request message and a return type that matches the response message.
The ProductService class in Example 3 shows how to do this. It overrides the GetProduct method to search for a product with the ID provided in the request. If the product is found, it returns the product data in a GetProductResponse message. If the product is not found or is inactive, it throws an RpcException.
Here are some key things to keep in mind when handling a gRPC call:
- The method you override should have a parameter that matches the request message.
- The method should return a response message that matches the return type.
- You can throw an RpcException if an error occurs.
By following these guidelines, you can create a robust and maintainable service that handles gRPC calls correctly.
Status Codes
Status Codes are a crucial part of understanding how service calls work. They help us interpret the result of a request and determine what went wrong.
A 0 status code means it was OK, which is the default status. This is the best possible outcome for a service call.
HTTP requests have their own set of status codes, such as 200 for OK, 400 for bad request, and 500 for internal error. But gRPC calls have a different list of status codes.
Here's a quick reference list of some common gRPC status codes:
A 3 status code means there was an invalid argument, which is equivalent to a bad request. This is a common error that can happen when the data passed to the service call is incorrect.
A 5 status code means the requested resource was not found. This could be because the product doesn't exist on the database or if the product is disabled.
Testing the Service
Testing the Service is a crucial step in ensuring your C# gRPC service is working as expected. After running your gRPC service using dotnet run, the service will start listening for incoming requests.
You won't be able to test it directly using a regular browser or HTTP client like Postman because gRPC uses HTTP/2. Instead, you can use tools like BloomRPC or grpcurl to test your gRPC services.
These specialized tools are designed to handle the unique requirements of gRPC, making it easier to test and debug your service.
Greeter Sample
The Greeter sample is a simple gRPC service where a client sends a request with a name and the server responds with a message followed by the name.
It's based on a common service definition in a proto file, which is included in the Greeter project.
The client and server are built on top of this common definition, making it easy to understand and work with.
To run the Greeter sample, you'll need to start the Greeter Server first, which can be done by running the executable in the bin > Debug folder.
Next, you'll need to run the Greeter Client in a separate command prompt, also in the bin > Debug folder.
Once you've run both, you should see the client sending a request and receiving a response from the server, which will print out the response in the console: Greeting: Hello World.
The Greeter Client is the client side of the gRPC service, with Program.cs as the entrypoint.
It creates a channel to talk to the server and then creates a client with the channel from the generated stub.
The Greeter project is a great starting point for learning about gRPC services in C#.
Featured Images: pexels.com


