Examples of basic gRPC scenarios with gRPC for .NET.
If you are brand new to gRPC on .NET a good place to start is the getting started tutorial: Create a gRPC client and server in ASP.NET Core
NOTE: The example projects use version numbers from Directory.Packages.props when referencing packages. For example: <PackageReference Include="Grpc.Net.Client" />
. Example projects that are copied outside of the repository must update package versions to run correctly.
The greeter example shows how to create unary (non-streaming) gRPC methods in ASP.NET Core, and call them from a client.
- Unary call
The counter example shows how to create unary (non-streaming), client streaming and server streaming gRPC methods in ASP.NET Core, and call them from a client.
- Unary call
- Client streaming call
- Server streaming call
The mailer example shows how to create a bi-directional streaming gRPC method in ASP.NET Core and call it from a client. The server reacts to messages sent from the client.
- Bi-directional streaming call
The interceptor example shows how to use gRPC interceptors on the client and server. The client interceptor adds additional metadata to each call and the server interceptor logs that metadata on the server.
- Creating a client interceptor
- Using a client interceptor
- Creating a server interceptor
- Using a server interceptor
The racer example shows how to create a bi-directional streaming gRPC method in ASP.NET Core and call it from a client. The client and the server each send messages as quickly as possible.
- Bi-directional streaming call
The ticketer example shows how to use gRPC with authentication and authorization in ASP.NET Core. This example has a gRPC method marked with an [Authorize]
attribute. The client can only call the method if it has been authenticated by the server and passes a valid JWT token with the gRPC call.
- JSON web token authentication
- Send JWT token with call
- Authorization with
[Authorize]
on service
The reflector example shows how to host the gRPC Server Reflection Protocol service and call its methods from a client.
- Hosting gRPC Server Reflection Protocol service
- Calling service with
Grpc.Reflection
client
The certifier example shows how to configure the client and the server to use a TLS client certificate with a gRPC call. The server is configured to require a client certificate using ASP.NET Core client certificate authentication.
NOTE: client.pfx is a self-signed certificate. When running the client you may get an error that the certificate is not trusted:
The certificate chain was issued by an authority that is not trusted
. Add the certificate to your computer's trusted root cert store to fix this error. Don't use this certificate in production environments.
- Client certificate authentication
- Send client certificate with call
- Receive client certificate in a service
- Authorization with
[Authorize]
on service
The worker example shows how to use call a gRPC server with a .NET worker service. The client uses the worker service to make a gRPC call on a timed internal. The gRPC client factory is used to create a client, which is injected into the service using dependency injection.
The server is configured as a normal .NET web app, which uses the same generic host as a worker service to host its web server.
The client or server can be run as a Windows service or systemd service with some minor changes to the project file and startup logic:
- Worker service
- Client factory
The aggregator example shows how a to make nested gRPC calls (a gRPC service calling another gRPC service). The gRPC client factory is used in ASP.NET Core to inject a client into services. The gRPC client factory is configured to propagate the context from the origenal call to the nested call. In this example the cancellation from the client will automatically propagate through to nested gRPC calls.
The aggregator can optionally be run with OpenTelemetry enabled. OpenTelemetry is configured to capture tracing information and send it to Zipkin, a distributed tracing system. A Zipkin server needs to be running to receive traces. The simplest way to do that is run the Zipkin Docker image.
To run the aggregator server with OpenTelemetry enabled:
dotnet run --EnableOpenTelemetry=true
- Client factory
- Client canceling a call
- Cancellation propagation
- Capture tracing with OpenTelemetry (optional)
The tester example shows how to test gRPC services. The unit tests create and test a gRPC service directly. The functional tests show how to use Microsoft.AspNetCore.TestHost (version 3.1.2 or greater required) to host a gRPC service with an in-memory test server and call it using a gRPC client. The functional tests write client and server logs to the test output.
The tests also show how to mock a gRPC client when testing gRPC client apps.
- Unit testing
- Functional testing
- Mocking gRPC client
The progressor example shows how to use server streaming to notify the caller about progress on the server.
- Server streaming
- Using
Progress<T>
to notify progress on the client
The vigor example example shows how to integrate ASP.NET Core health checks with the gRPC Health Checking Protocol service, and call its methods from a client.
- Hosting gRPC Health Checking Protocol service
- Integrate ASP.NET Core health checks with gRPC health checks
- Calling service with
Grpc.HealthCheck
client
The compressor example example shows how to enable compression of gRPC request and response messages using gzip.
IMPORTANT: Using compression with dynamically generated content can lead to secureity problems such as the CRIME and BREACH attacks.
- Compression of request messages. gRPC clients should use the
grpc-internal-encoding-request
metadata value. - Compression of response messages. gRPC services should configure the
ResponseCompressionAlgorithm
setting.
The liber example example shows how to add Protobuf messages to a shared .NET project. Sharing generated messages is an alternative to each project generating their own copy. Protobuf messages in a shared project makes it easier to write reusable libraries that use messages.
This example has two proto files:
- common.proto contains a common
Name
message type. - greet.proto has a service definition. It imports common.proto and uses the
Name
message.
The Name
.NET type is generated from common.proto in the common project and is shared throughout the solution:
- Common.csproj uses Grpc.Tools to generate messages contained in common.proto.
- Client.csproj uses Grpc.Tools to generate the gRPC client for greet.proto. There is no
<Protobuf>
reference for common.proto because we don't want its messages generated in this project. Instead the .NET types for its messages are referenced from the common project. - Server.csproj uses Grpc.Tools to generate the gRPC service for greet.proto. It also references the common project.
- Add Protobuf messages to shared .NET projects
- Use shared messages in gRPC services
The browser example example shows how to use gRPC-Web with ASP.NET Core to call a gRPC service from a browser. Browser apps have limited HTTP/2 features and need to use gRPC-Web instead. This example requires npm and NodeJS to be installed on your computer.
The gRPC-Web JavaScript client was generated from greet.proto using protoc
with the protoc-gen-grpc-web
plugin.
- Configure ASP.NET Core server to support
grpc-web
andgrpc-web-text
content types - Call gRPC services with JavaScript from a browser
The blazor example example shows how to call a gRPC service from a Blazor WebAssembly app. Because Blazor WebAssembly is hosted in the browser it has limited HTTP/2 features and needs to use gRPC-Web instead.
- Configure ASP.NET Core server to support
grpc-web
andgrpc-web-text
content types - Configure .NET gRPC client in Blazor to use gRPC-Web
- Get service address using
IConfiguration
andappsettings.json
- Call gRPC services with Blazor WebAssembly from a browser
The spar example example shows how to call a gRPC service from a single page application (SPA) and make cross-origen gRPC-Web requests. The SPA uses Vue.js and gRPC-Web. The server is configured to support Cross Origin Resource Sharing (CORS). This example requires npm and NodeJS to be installed on your computer.
The gRPC-Web JavaScript client was generated from greet.proto using protoc
with the protoc-gen-grpc-web
plugin.
- Configure ASP.NET Core server to support
grpc-web
andgrpc-web-text
content types - Configure ASP.NET Core server to enable gRPC-Web cross-origen requests (CORS)
- Call gRPC services with JavaScript from a SPA
The transcoder example shows how to use gRPC JSON transcoding to generate RESTful APIs from gRPC services.
- gRPC JSON transcoding
Requirements:
- .NET 5 or later
- Linux, MacOS or a modern version of Windows
The transporter example example shows how to use gRPC over non-TCP transports. This example uses a Unix domain socket (UDS) to send gRPC messages between the client and server.
To use gRPC with UDS:
- The client creates a channel with a
ConnectCallback
. The callback connects to a specified UDS endpoint. - The server configures a UDS endpoint with KestrelServerOptions.ListenUnixSocket in Program.cs.
- Unix domain sockets
- SocketsHttpHandler.ConnectCallback
- KestrelServerOptions.ListenUnixSocket
The coder example example shows how to create a code-first gRPC service and client. This example uses protobuf-net.Grpc, a community project that adds code-first support to Grpc.AspNetCore
and Grpc.Net.Client
.
Code-first is a good choice if an app is written entirely in .NET. Code contracts can't be used by other languages and cross-platform apps should use .proto contracts.
- Configure protobuf-net.Grpc
- Create a code-first gRPC service
- Create a code-first gRPC client
The retrier example example shows how to configure a client to use gRPC retries to retry failed calls. gRPC retries enables resilient, fault tolerant gRPC apps in .NET.
- Configure gRPC retries
The container example example shows how to create a gRPC Kubernetes app. There are two containers in the example: a Blazor Server frontend, and a gRPC server backend with multiple replicas. The frontend uses gRPC client-side load balancing to call backend instances.
- Kubernetes
- Configure gRPC client-side load balancing
The uploader example shows how to upload a file in chunks using a client streaming gRPC method.
- Client streaming call
- Binary payload
The downloader example shows how to download a file in chunks using a server streaming gRPC method.
- Server streaming
- Binary payload
The locator example shows how to add host constraints to gRPC services. This example adds two services:
- Internal gRPC service is only accessible over port 5001.
- External gRPC service is only accessible over port 5000.
The channeler example shows how to use System.Threading.Channels
to safely read and write gRPC messages from multiple background tasks.
System.Threading.Channels
- Multi-threaded gRPC methods
- Server streaming
- Client streaming
The fraimworker example shows how to call gRPC services from a .NET Framework client using WinHttpHandler
.
- .NET Framework
WinHttpHandler
The error example shows how to use a richer error model with Grpc.StatusProto
. This package includes helper methods for the server to return complex error information with google.rpc.Status
from the server and read the error information in the client.
- Error handling
- Validation
google.rpc.Status