Create a gRPC client and server in ASP.NET Core-Client

Consuming gRPC Services in .NET Core

gRPC is a powerful and efficient communication protocol that allows you to define and consume APIs in various programming languages. In this tutorial, we will explore how to consume gRPC services in a .NET Core client application. We’ll use the gRPC service we previously created and walk through the steps to interact with it from a client application.

Prerequisites

Before getting started, make sure you have the following:

  • .NET Core SDK installed
  • Access to the gRPC service you want to consume (you can follow the earlier tutorial on creating a gRPC service)

Go to Client app that we created in previous blog post and install following nuget package

  1. Install NuGet Packages: Install the necessary NuGet packages for gRPC client communication:

    dotnet add package Grpc.Net.Client
    dotnet add package Google.Protobuf
    dotnet add package Grpc.Tools
    

Consuming the gRPC Service

Now, let’s consume the gRPC service we previously created. Open the Program.cs file in your console application project and replace its contents with the following code:

using System;
using System.Threading.Tasks;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using Grpc.Net.Client;
using GrpcService.Protos;

namespace GrpcClientApp
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var channel = GrpcChannel.ForAddress("https://localhost:7029");
            TodoServiceGrpc.TodoServiceGrpcClient client = new(channel);

            // Add ToDo items
            var todo1 = await client.AddTodoAsync(new TodoItem { Title = "Buy groceries", Completed = false });
            var todo2 = await client.AddTodoAsync(new TodoItem { Title = "Read a book", Completed = true });

            Console.WriteLine($"Added ToDo: ID = {todo1.Id}");
            Console.WriteLine($"Added ToDo: ID = {todo2.Id}");

            try
            {
                using var call = client.GetTodos(new Empty());

                Console.WriteLine("Retrieving all ToDos:");

                await foreach (var todo in call.ResponseStream.ReadAllAsync())
                {
                    Console.WriteLine($"Todo ID: {todo.Id}, Title: {todo.Title}, Completed: {todo.Completed}");
                }
            }
            catch (RpcException ex) when (ex.StatusCode == StatusCode.Unimplemented)
            {
                Console.WriteLine("GetTodos method is not implemented on the server.");
            }

            Console.ReadLine();
        }
    }
}

In this code, we first establish a connection to the gRPC service using the GrpcChannel. Then, we create an instance of the TodoServiceGrpcClient using the channel.

We use the client to call the AddTodoAsync method, adding two todo items and printing their IDs. Next, we use the client to call the GetTodos method and retrieve a stream of all todo items. We print each todo item’s information using a foreach loop and the ResponseStream.ReadAllAsync method.

Updating the .csproj File

For successful code generation and proper referencing of packages and project dependencies, ensure that your .csproj file includes the following sections:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net7.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <!-- OTHERS -->
  
  <!-- Include the .proto file for code generation -->
  <ItemGroup>
    <Protobuf Include="..\GrpcService\Protos\Todo.proto" GrpcServices="Client">
      <Link>Protos\Todo.proto</Link>
    </Protobuf>
  </ItemGroup>

</Project>

Running the Client Application

With the client application code in place and the .csproj file updated, you’re ready to run it. In your terminal, navigate to the root of your GrpcClientApp directory and run the following command:

dotnet run 


You should see output indicating the successful addition of todo items and the retrieved todo items from the server.

Conclusion

In this tutorial, you learned how to consume gRPC services in a .NET Core client application. By leveraging the Grpc.Net.Client package, you can easily establish connections to gRPC services, make RPC calls, and process responses. gRPC offers a powerful and efficient way to communicate between services, and with the steps outlined in this tutorial, you can integrate gRPC communication into your .NET Core applications with ease.

Next Post Previous Post
No Comment
Add Comment
comment url