Said's Blog

.NET 7 - gRPC JSON tanscoding

August 03, 20223 min read
image

gRPC, like REST, is another way to communicate between apps. It uses the HTTP/2 protocol to exchange binary messages, which are serialized/deserialized using Protocol Buffers. Basically, protocol buffers is a binary serialization protocol, it is highly performant by providing a compact binary format that requires low CPU usage.

While using gRPC allows us to create high-performance, real-time services, REST+JSON can be used everywhere, and its human-readable JSON messages are easy to debug. Therefore, in order to have them both, Microsoft is working on a new feature that will be included in .NET 7.

gRPC JSON transcoding

gRPC JSON transcoding is an extension for ASP.NET Core that creates RESTful JSON APIs for gRPC services. Once the configuration set, it allows apps to call gRPC services with familiar HTTP concepts:

  • HTTP verbs
  • URL parameter binding
  • JSON requests/responses

Usage

The first step is to add a package reference to Microsoft.AspNetCore.Grpc.JsonTranscoding. Next, register it in server startup code by adding AddJsonTranscoding(). For instance, services.AddGrpc().AddJsonTranscoding(). The last step is adding google/api/http.proto and google/api/annotations.proto files to the project by importing google/api/annotations.proto to the gRPC proto file

							syntax = "proto3";

import "google/api/annotations.proto";

package greet;

service Greeter {
  rpc SayHello (HelloRequest) returns (HelloReply) {
    option (google.api.http) = {
      get: "/v1/greeter/{name}"
    };
  }
}

message HelloRequest {
  string name = 1;
}

message HelloReply {
  string message = 1;
}
						

In the example above, the SayHello gRPC method can be invoked as gRPC and as a RESTful API:

					    Request: HTTP/1.1 GET /v1/greeter/world
Response: { "message": "Hello world" }
					

And browser apps call it like any other RESTful API:

					    fetch('https://localhost:5001/v1/greeter/world')
.then((response) => response.json())
.then((result) => {
console.log(result.message); // Hello world
});
					

More details

  • MSDN
  • .NET Blog
  • ASP.NET Community Standup - gRPC Updates in .NET 7