gRPC server and .Net Core
Tags: grpc, protobuffers, netcore, grpcserver
Published: 2023-03-09 07:35:09

As developers, while building an API applications we find ourself between various choices of frameworks like _REST_, _SOAP_, _GraphQL_, _HTTP API_ and more. It can be difficult to for a developer to choose the correct one that caters the needs of the application.

In this post, I'd like to introduce you to gRPC, which is one of the newer approach. gRPC supports many languages like _C#/.Net_, _C++_, _Dart_, _Go_, _Java_ and other popular languages. Today we are focusing on how well gRPC integrates with ASP.Net Core.

By the end of this post, you'll have a basic understanding of what gRPC is, how it works with ASP.Net Core and whether it is right for your application or not. We will implement a Client/Server application, you can find the full working code in the Git repository, linked below.

Let's get started...

### What is gRPC?
gRPC stands for google Remote Procedure Calls. It was initially designed by Google to make distributed applications more manageable for both `Client` and `Server`. gRPC takes a refreshed look on the old RPC design by making it interoperable and efficient using Protocol Buffers and HTTP/2. The gRPC with Protocol Buffers is equivalent of JSON or XML with REST APIs. The HTTP/2 specification was published in 2015 and improved on the 20 year old HTTP/1.1 design.

### What is Protocol Buffers?
gRPC supports multiple serialization formats, but the most commonly used is Protocol Buffers. It is an open-source serialization structure specifically designed for efficiency and optimization. Data parsing with Protocol Buffers uses less CPU as the data is represented in a binary format which allows to minimize the size of encoded messages.


## gRPC & .Net Core
From the Microsoft side the .NET team have been working for bringing gRPC to the .NET community. Earlier you had a basic library which wasn't good as other libraries nor you had any project template helping you to set up your application with gRPC. Now we have better library and better support.

We’ll now create a gRPC application for both a `Server` and in the next post I'll show you the `Client`. While creating the gRPC application we will try to cater real life requirements as many as possible. For that we will create two independent applications one for the Client & one for the Server. We will send nested data from the `Client` including integer, string and datetime and also receive the response from the `Server` and process it.

### gRPC Setup
For the `Server` we will create a new AspNetCore Web App and add following packages. You can use any other template as you wish.

```
<ItemGroup>
    <PackageReference Include="Google.Protobuf" Version="3.22.1" />
    <PackageReference Include="Grpc.AspNetCore" Version="2.51.0" />
    <PackageReference Include="Grpc.AspNetCore.Web" Version="2.51.0" />
    <PackageReference Include="Grpc.Tools" Version="2.52.0">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
  </ItemGroup>
```

Now add a new `Protos` folder and create a new empty file named company.proto.

![proto folder](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tsipdt4mbyty0cd1xf87.png)

We’ll use the Proto Buffers to map out our gRPC service, a request, and a response. We will create a Company & Employee nested structure and a container for the response.

```
syntax = "proto3";

import "google/protobuf/timestamp.proto";

option csharp_namespace = "GrpcServer";

// The Company service definition.
service Company {
  // Sends a greeting
  rpc PostCompanyWithEmployees (CompanyModel) returns (Response);
}

// The request message containing the companies's details with employees.
message CompanyModel {
  int32 companyId = 1;
  string comapnyName = 2;
  repeated EmployeeModel employees = 3;
}

// The request message containing the employee's details.
message EmployeeModel {
  int32 empId = 1;
  string empName = 2;
  int32 companyId = 3;
  google.protobuf.Timestamp birthDate = 4;
}

// The response message containing the response status.
message Response {
  int32 status = 1;
}
```
Now, just save and build the application. Following line will get added `.csproj` file.

```
<ItemGroup>
  <Protobuf Include="Protos\company.proto" GrpcServices="Server" />
</ItemGroup>
```
We should notice the GrpcServices attribute. It tells which side the application will be on, `Server` or `Client`. In above case, it is showing as `Server` where as in the other application it will be as `Client`. In case of where the `Server` and `Client` both are in same project it will be as `Server,Client`.


Now in the `Server` application, create a method with name `PostCompanyWithEmployees` and expecting `CompanyModel` as input with `gRPC.Respose` as return type.

```
public override Task<Response> PostCompanyWithEmployees(CompanyModel request, ServerCallContext context)
        {
            try
            {
                //Add your database/API call here to save the Employee & Company details.
                //After successful post call return the Status as 1 else 0.
                return Task.FromResult(new Response
                {
                    Status = 1
                });
            }
            catch
            {
                return Task.FromResult(new Response
                {
                    Status = 0
                });
            }            
        }
```
I have created a separate post for the Client application [here](https://dev.to/prasannaupatankar/grpc-client-and-net-core-4gm7).
Once all is done, we will run both the applications and call the Server and we should get a response from the it. In our case the `Server` will respond with an integer. We’ll see the results in console output window.

![Colsole output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/it2tes1l6ips4i5ptl7y.png)

Congratulations! We just successfully built a `Client` and `Server` gRPC application.

### References
* Git repository for [gRPC Client](https://github.com/prasannaupatankar/GRPCClient-NetCore/tree/dev) application
* Git repository [gRPC Server] (https://github.com/prasannaupatankar/GrpcServer-NetCore/tree/dev) application
* Official [gRPC site](https://grpc.io/)
* Microsoft's documentation for [gRPC on .Net Core](https://learn.microsoft.com/en-us/aspnet/core/grpc/?view=aspnetcore-3.1)

Cover photo by [Karim MANJRA](https://unsplash.com/@karim_manjra?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/photos/tJnwbgDg84U?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)