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?
answer
- Grpc.AspNetCore metapackage
- <Protobuf GrpcServices="Server">
- override the generated ...Base class
- AddGrpc, then MapGrpcService<T>()
- Kestrel EndpointDefaults Protocols Http2
basics
~10 sReference 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 sThe `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<ItemGroup>
<Protobuf Include="Protos\pricequote.proto" GrpcServices="Server" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Grpc.AspNetCore" Version="2.84.0" />
</ItemGroup>go deeper
Recall the chain: .proto item, generated base class, override, AddGrpc, MapGrpcService, and that the template restricts Kestrel to HTTP/2.
Explain the Protobuf item metadata, where generated code lives, how the service instance is created per call, and the 426 for HTTP/1.1.
Configure message size limits and detailed errors per environment, and decide how the shared .proto is consumed by server and client projects.
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.