skip to content

With ASP.NET Core 10 gRPC JSON transcoding, how do you expose the price-quote service as a JSON HTTP API, and what are its limits?

level: seniorimportance: nice to knowfreq 15%

answer

  1. Microsoft.AspNetCore.Grpc.JsonTranscoding
  2. AddGrpc().AddJsonTranscoding()
  3. <IncludeHttpRuleProtos>true</IncludeHttpRuleProtos>
  4. option (google.api.http) per rpc
  5. no client or bidirectional streaming

basics

~10 s

Add Microsoft.AspNetCore.Grpc.JsonTranscoding, call AddGrpc().AddJsonTranscoding(), set IncludeHttpRuleProtos to import google/api/annotations.proto, and annotate each rpc with option (google.api.http). Only annotated unary and server-streaming methods become JSON endpoints.

solid answer

~40 s

JSON transcoding ships in the aspnetcore repo as `Microsoft.AspNetCore.Grpc.JsonTranscoding`. You change `AddGrpc()` to `AddGrpc().AddJsonTranscoding()`, add `<IncludeHttpRuleProtos>true</IncludeHttpRuleProtos>` so the package's bundled `google/api/annotations.proto` and `http.proto` are on Grpc.Tools' import path, and annotate rpcs, for example `option (google.api.http) = { get: "/v1/quotes/{symbol}" };`. The same `PriceQuoteService` then answers `GET /v1/quotes/ACME` with JSON and still serves gRPC. Route parameters, the `body` field and query strings fill the request message; gRPC statuses map to HTTP codes, so `NotFound` becomes 404. Methods without an http rule are not exposed; unary and server-streaming methods work (server streams as line-delimited JSON), client and bidirectional streaming do not. `GrpcJsonTranscodingOptions.JsonSettings` controls output, and the docs mark `Microsoft.AspNetCore.Grpc.Swagger` deprecated.

code

proto · 15 lines
proto
syntax = "proto3";

import "google/api/annotations.proto";

option csharp_namespace = "Pricing";
package pricing;

service PriceQuote {
  rpc GetQuote (QuoteRequest) returns (QuoteReply) {
    option (google.api.http) = {
      get: "/v1/quotes/{symbol}"
    };
  }
  rpc StreamQuotes (QuoteSubscription) returns (stream QuoteReply);  // gRPC only
}

go deeper

for a junior

Recall that transcoding lets one gRPC service answer JSON HTTP requests and that each rpc needs a google.api.http annotation.

for a middle

Explain the setup steps, IncludeHttpRuleProtos, route, body and query binding, and how gRPC statuses become HTTP codes.

for a senior

Judge when transcoding fits: unary and server-streaming only, HTTP/1.1 endpoint changes, JSON settings, and how the API will be documented now Grpc.Swagger is deprecated.

for a principal

Decide whether a JSON surface should be generated from gRPC contracts or designed separately, and who owns compatibility for both.

## What transcoding is **JSON transcoding** lets one gRPC service also answer ordinary HTTP requests with JSON bodies. The incoming HTTP request is mapped onto the rpc's request message, the gRPC method runs as usual, and the response message is written as JSON. Unlike gRPC-Web, the caller needs no gRPC library: any HTTP client, script or partner tool can call it. The feature ships in the **aspnetcore** repository, not in grpc-dotnet. ## Setting it up 1. Reference `Microsoft.AspNetCore.Grpc.JsonTranscoding`. 2. Register it: `builder.Services.AddGrpc().AddJsonTranscoding();`. 3. Add `<IncludeHttpRuleProtos>true</IncludeHttpRuleProtos>` to the project. The package's build targets then add its bundled `google/api/annotations.proto` and `google/api/http.proto` to `Protobuf_StandardImportsPath`, so you do not copy them into the project. 4. Annotate each rpc you want exposed with `option (google.api.http)`. ## Binding rules - **Route:** `get: "/v1/quotes/{symbol}"` binds the `symbol` field from the path. - **Body:** `post: "/v1/quotes"` with `body: "*"` deserializes the whole JSON body into the request message; `body: "basket"` binds only that field. - **Query string:** request fields not bound by the route or body can be set with query parameters. - **Response:** the whole response message is serialized unless `response_body` selects one field. ## Status mapping A thrown `RpcException` becomes an HTTP status plus a JSON error body: | gRPC status | HTTP status | |---|---| | `InvalidArgument`, `FailedPrecondition`, `OutOfRange` | 400 | | `Unauthenticated` | 401 | | `PermissionDenied` | 403 | | `NotFound` | 404 | | `AlreadyExists`, `Aborted` | 409 | | `ResourceExhausted` | 429 | | `Unimplemented` | 501 | | `Unavailable` | 503 | | `DeadlineExceeded` | 504 | `FailedPrecondition` deliberately maps to 400, not 412. ## Limits - **Only annotated methods.** An rpc without an http rule stays gRPC-only; there is no automatic route. - **Streaming.** Unary and server-streaming methods are transcoded. Server streams are written as line-delimited JSON, one message per line, and `WriteIndented` does not apply to them. Client-streaming and bidirectional methods with an http rule are skipped with a log message. - **HTTP/1.1 clients** need a Kestrel endpoint that allows HTTP/1.1; the `grpc` template's `Http2` default must change to `Http1AndHttp2`. - **OpenAPI.** The `Microsoft.AspNetCore.Grpc.Swagger` package that described transcoded endpoints was experimental and the docs now mark it deprecated with no direct replacement, so plan for documenting a transcoded API separately. ## Serializer settings `AddJsonTranscoding(o => o.JsonSettings = new GrpcJsonSettings { ... })` controls output. Its flags all default to false: `WriteIndented`, `IgnoreDefaultValues`, `WriteEnumsAsIntegers`, `WriteInt64sAsStrings`, `PropertyNameCaseInsensitive` and `RemoveEnumPrefix`. `TypeRegistry` resolves `Any` payloads. ## What a JSON caller sees For `GetQuote` annotated with `get: "/v1/quotes/{symbol}"`: - `GET /v1/quotes/ACME` runs the gRPC method with `Symbol = "ACME"` and returns the reply as JSON. - Property names are the protobuf JSON names, lowerCamelCase by default (`symbol`, `inStock`), not the C# property names. - `GET /v1/quotes/XYZ` for an unknown symbol returns 404 with a JSON error body carrying the status code and message. - Log output shows the gRPC endpoint executing for the HTTP request, which is a quick way to confirm the route was transcoded. Because the gRPC method runs unchanged, interceptors, authorization and `ServerCallContext` work for JSON callers too; `context.GetHttpContext()` returns the HTTP request that was transcoded. ## Transcoding or gRPC-Web? Choose transcoding when callers want a plain JSON API, such as partners or scripts; choose gRPC-Web when the caller is your own browser code with a generated gRPC-Web client that keeps protobuf messages and server streaming semantics.

  • GetQuote throws RpcException with StatusCode.NotFound. What does a JSON caller of GET /v1/quotes/XYZ receive?
    HTTP 404 with a JSON error body describing the status and message. Transcoding maps gRPC status codes to HTTP status codes, so the same exception still produces the `NotFound` gRPC status for gRPC callers.
  • Why does the build fail to find google/api/annotations.proto after adding the package?
    The package only adds its bundled protos to Grpc.Tools' import path when the project sets `IncludeHttpRuleProtos` to true. Without the property, `protoc` cannot resolve the import; set it rather than copying the files into the project.

  • AddJsonTranscoding exposes every rpc automatically as POST /package.Service/Method.
  • Transcoding replaces gRPC, so the service stops answering gRPC clients.
  • Client-streaming rpcs can be transcoded if the body is set to "*".
  • JSON transcoding ships in grpc-dotnet's Grpc.AspNetCore.Web package.
  • A NotFound RpcException reaches JSON callers as 200 with an error field.

Assumes ASP.NET Core 10.0.12: JSON transcoding and the IncludeHttpRuleProtos build target ship in the aspnetcore repo at that release, and the current docs mark Microsoft.AspNetCore.Grpc.Swagger deprecated.