skip to content

Hosting gRPC Services

ASP.NET Core hosts gRPC through AddGrpc and MapGrpcService over HTTP/2, with Grpc.Tools generating base classes from .proto files. Interviewers probe streaming, interceptors, gRPC-Web and transcoding.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

6

In ASP.NET Core 10, how do you host a gRPC service defined in a .proto file, and what do Grpc.Tools, AddGrpc and MapGrpcService each do?

level: juniorimportance: must knowfreq 50%

answer

  1. Grpc.AspNetCore metapackage
  2. <Protobuf GrpcServices="Server">
  3. override the generated ...Base class
  4. AddGrpc, then MapGrpcService<T>()
  5. Kestrel EndpointDefaults Protocols Http2

basics

~10 s

Reference Grpc.AspNetCore, add the .proto as a <Protobuf> item so Grpc.Tools generates a base class at build time, override its methods, then call builder.Services.AddGrpc() and app.MapGrpcService<T>(). Calls must arrive over HTTP/2.

solid answer

~40 s

The `Grpc.AspNetCore` package brings the server, `Google.Protobuf` and `Grpc.Tools`. A `<Protobuf Include="Protos\pricequote.proto" GrpcServices="Server" />` item makes Grpc.Tools run `protoc` on every build and write C# into `obj`: message classes plus a `PriceQuote.PriceQuoteBase` class with one virtual method per rpc. Your `PriceQuoteService` derives from it and overrides `GetQuote(QuoteRequest request, ServerCallContext context)`. `builder.Services.AddGrpc()` registers the gRPC server services and returns an `IGrpcServerBuilder` for options; `app.MapGrpcService<PriceQuoteService>()` maps each rpc as a POST endpoint such as `/pricing.PriceQuote/GetQuote`. The service is created per call from the request's services unless you register it yourself. gRPC needs HTTP/2, so `dotnet new grpc` sets Kestrel's `EndpointDefaults:Protocols` to `Http2`; an HTTP/1.1 request that does reach a gRPC endpoint gets 426.

code

xml · 7 lines
xml
<ItemGroup>
  <Protobuf Include="Protos\pricequote.proto" GrpcServices="Server" />
</ItemGroup>

<ItemGroup>
  <PackageReference Include="Grpc.AspNetCore" Version="2.84.0" />
</ItemGroup>

go deeper

for a junior

Recall the chain: .proto item, generated base class, override, AddGrpc, MapGrpcService, and that the template restricts Kestrel to HTTP/2.

for a middle

Explain the Protobuf item metadata, where generated code lives, how the service instance is created per call, and the 426 for HTTP/1.1.

for a senior

Configure message size limits and detailed errors per environment, and decide how the shared .proto is consumed by server and client projects.

for a principal

Decide where gRPC fits beside JSON endpoints across services, and who owns contract changes once several teams compile against one .proto.

## The moving parts An ASP.NET Core gRPC service is ordinary ASP.NET Core hosting plus generated code. The pieces: | Piece | Role | |---|---| | `.proto` file | the contract: messages and a `service` with its rpc methods | | `Grpc.Tools` | MSBuild integration that runs `protoc` and the C# gRPC plugin during build | | `Grpc.AspNetCore` | metapackage: the server (`Grpc.AspNetCore.Server`), `Google.Protobuf`, `Grpc.Tools` and the client factory | | `AddGrpc()` | registers the gRPC server services in DI | | `MapGrpcService<T>()` | maps the service's methods into endpoint routing | ## Code generation from the .proto The project file lists the contract as a `Protobuf` item. Grpc.Tools reads its metadata: - `GrpcServices` chooses what is generated: `Both` (the default), `Server`, `Client` or `None` (messages only). - `Access` defaults to `Public`; `Internal` makes generated types internal. - `OutputDir` defaults to the intermediate output path, so generated files live under `obj`, not in source control. For a contract with `option csharp_namespace = "Pricing";` and `service PriceQuote`, the build produces message classes such as `QuoteRequest` and a static `PriceQuote` class holding the abstract base class `PriceQuote.PriceQuoteBase`. Every rpc becomes a virtual method; one you do not override answers with the `Unimplemented` status. ## Registration and mapping 1. `builder.Services.AddGrpc(options => ...)` registers the server. The options (`GrpcServiceOptions`) include `MaxReceiveMessageSize` (4 MB by default), `MaxSendMessageSize` (unlimited by default), `EnableDetailedErrors` and `Interceptors`. 2. `app.MapGrpcService<PriceQuoteService>()` adds one endpoint per rpc. Each is a POST endpoint whose path is the method's full name, `/pricing.PriceQuote/GetQuote`, and it returns a `GrpcServiceEndpointConventionBuilder`, so `RequireAuthorization()` or `EnableGrpcWeb()` can be chained. 3. Per call, the service class is resolved from the request's service provider if you registered it; otherwise it is created with its constructor dependencies and disposed after the call. Constructor injection of scoped services such as a `DbContext` is therefore safe. ## HTTP/2 is required The server checks the request protocol before running a handler. Over HTTP/2 (or HTTP/3) the call proceeds; over HTTP/1.1 it answers **426 Upgrade Required** with an `Upgrade: HTTP/2` header and the message "Request protocol 'HTTP/1.1' is not supported." The `grpc` template therefore writes this into `appsettings.json`: - `"Kestrel": { "EndpointDefaults": { "Protocols": "Http2" } }` Serving HTTP/1.1 and HTTP/2 on the same port requires TLS, because the protocol is negotiated during the TLS handshake. Kestrel endpoint configuration itself is a hosting topic. ## Errors from a handler - Throw `new RpcException(new Status(StatusCode.NotFound, "No quote for XYZ"))` to return a specific status and message. - Any other exception becomes `StatusCode.Unknown` with "Exception was thrown by handler."; the exception text is added only when `EnableDetailedErrors` is true, which belongs in Development only. ## What the template creates `dotnet new grpc` writes `Protos/greet.proto` with `GrpcServices="Server"`, a `GreeterService` deriving from `Greeter.GreeterBase`, `AddGrpc()`, `MapGrpcService<GreeterService>()` and a `GET /` that tells browsers to use a gRPC client. The ASP.NET Core 10.0.12 template pins `Grpc.AspNetCore` 2.64.0, older than the current 2.84 release, so a new project is worth updating before work starts. ## Sharing one contract between server and clients The price-quote contract is consumed by the service and by every back end that calls it. Common layouts: - Keep the `.proto` files in one folder or repository and reference them from each project with `<Protobuf Include="..\contracts\pricequote.proto" GrpcServices="Client" Link="Protos\pricequote.proto" />`, so each side generates only what it needs. - The `dotnet-grpc` global tool writes these items: `dotnet-grpc add-file ..\contracts\pricequote.proto --services Server` adds the reference with the chosen services value, and `add-url` downloads a contract from a URL. - Avoid one shared class library that generates `Both` for everyone unless the server and clients really ship together; it couples their release cadence to the library's. Whatever the layout, generated code is rebuilt from the `.proto` on every build, so the contract file, not the generated C#, is what goes through review.

  • A caller sends a 6 MB request message to the price-quote service. What happens and how do you change it?
    `MaxReceiveMessageSize` defaults to 4 MB, so the server fails the call with `ResourceExhausted` and "Received message exceeds the maximum configured message size." Raise it globally in `AddGrpc(o => o.MaxReceiveMessageSize = ...)` or for one service with `AddServiceOptions<PriceQuoteService>(...)`; a `null` value removes the limit. The .NET client has the same 4 MB receive default.
  • Why might you register PriceQuoteService in DI yourself?
    Only when you want a lifetime other than per call, for example a singleton holding expensive state. If the type is registered, the activator takes that instance and does not dispose it; otherwise it creates one per call with constructor injection and disposes it afterwards.

  • The generated C# files must be committed, because Grpc.Tools only runs once.
  • A gRPC service class is a singleton unless it is registered with AddScoped.
  • MapGrpcService works over HTTP/1.1 as well, so the template's Http2 setting is optional.
  • An unhandled exception in a handler is returned to the caller with its full message by default.
  • GrpcServices="Both" is required on the server, or MapGrpcService cannot find the service.

Assumes ASP.NET Core 10 with Grpc.AspNetCore 2.84; the 10.0.12 grpc template still pins Grpc.AspNetCore 2.64.0, and the template's Http2-only Kestrel default is read from that release.

open as a page

In ASP.NET Core gRPC, how do you write and register a server interceptor, and how does it differ from ASP.NET Core middleware?

level: middleimportance: should knowfreq 33%

basics

~10 s

Derive from Interceptor, override UnaryServerHandler (and the streaming handlers you need), and register it with AddGrpc(o => o.Interceptors.Add<T>()) or AddServiceOptions<TService>. Unlike middleware it runs only for gRPC calls and sees typed messages and ServerCallContext.

open as a page

In an ASP.NET Core gRPC service, how do you implement a server-streaming method, and what does ServerCallContext give the handler?

level: middleimportance: should knowfreq 38%

basics

~10 s

Override the generated method, which receives the request, an IServerStreamWriter<T> and a ServerCallContext; loop calling WriteAsync until context.CancellationToken fires. ServerCallContext carries the deadline, cancellation token, headers, trailers, status and, through GetHttpContext(), the HttpContext.

open as a page

When an ASP.NET Core gRPC service calls another gRPC service, how do AddGrpcClient, deadlines and EnableCallContextPropagation keep the chain bounded?

level: seniorimportance: should knowfreq 30%

basics

~10 s

Register the downstream client with AddGrpcClient<T>(o => o.Address = ...), pass a deadline on each call, and add EnableCallContextPropagation() so calls made inside a gRPC handler inherit the incoming call's deadline and cancellation token.

open as a page

How do you let a browser call an ASP.NET Core gRPC price-quote service through gRPC-Web, and what must change in the app's configuration?

level: seniorimportance: nice to knowfreq 22%

basics

~10 s

Add Grpc.AspNetCore.Web, call app.UseGrpcWeb(), opt the service in with EnableGrpcWeb() because GrpcWebOptions.DefaultEnabled is false, allow HTTP/1.1 on the Kestrel endpoint, and for cross-origin pages add a CORS policy exposing the grpc-status headers.

open as a page

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%

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.

open as a page