gRPC contracts and streaming
gRPC contracts and streaming
gRPC is a contract-oriented remote procedure call framework. A .proto file defines service methods and message fields; build tools generate typed client and server code. A unary call sends one request and receives one response; streaming methods can send multiple messages over the call.
Native ASP.NET Core gRPC uses HTTP/2. Protocol Buffers field numbers identify fields on the wire: do not renumber or reuse removed field tags; reserve them instead. Add compatible optional information rather than breaking existing consumers. Four method shapes exist: unary, server streaming, client streaming and bidirectional streaming. A deadline limits how long the caller is willing to wait, and server operations should observe cancellation; a client timeout does not prove a mutation never occurred. gRPC status codes communicate RPC outcomes, distinct from ordinary HTTP status handling. Await stream writes serially and do not read from the same stream concurrently. One reader and one writer may operate concurrently on a bidirectional call, but each direction must have its own serialized access. Keep all call-owned work within the call lifetime; propagate cancellation and do not extend the parent deadline when creating a child call. A deadline error is not proof that a server-side effect did not commit. Browser clients generally need a compatible bridge such as gRPC-Web, which has streaming restrictions. The lab uses cleartext HTTP/2 on an ephemeral loopback port only; real services require authenticated TLS and authorization. Dependencies are pinned to listed package versions, not a claim that they are latest or security-approved. Review restore graph and advisories before executing.
Baseline: .NET 10 / C# 14. In an approved environment use the complete fixture project, restore only reviewed dependencies from approved sources, then run dotnet build --no-restore and dotnet run --no-build --no-launch-profile. Blazor projects use localhost:5087; stop the server with Ctrl+C. Other examples start a bounded local server and client in one process. No real credentials or external services. Expected results are reasoned, not executed.
Call a typed unary method
The companion proto generates both the client and the server base class.
using Fixture.Contracts;using Grpc.Core;using Grpc.Net.Client;using Microsoft.AspNetCore.Server.Kestrel.Core;using System.Net;var builder = WebApplication.CreateBuilder(args);builder.Logging.ClearProviders();builder.WebHost.ConfigureKestrel(o => o.Listen(IPAddress.Loopback, 0, l => l.Protocols = HttpProtocols.Http2));builder.Services.AddGrpc();await using var app = builder.Build();app.MapGrpcService<StockEndpoint>();using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(timeout.Token);try { using var channel = GrpcChannel.ForAddress(app.Urls.Single()); var client = new StockService.StockServiceClient(channel); var deadline = DateTime.UtcNow.AddSeconds(5);var result = await client.GetAsync(new StockRequest { Id = 1 }, deadline: deadline, cancellationToken: timeout.Token);Console.WriteLine(result.Quantity);} finally { await app.StopAsync(); }public class StockEndpoint : StockService.StockServiceBase { public override Task<StockReply> Get(StockRequest request, ServerCallContext context) { if (request.Id != 1) throw new RpcException(new Status(StatusCode.NotFound, "Unknown sample")); return Task.FromResult(new StockReply { Quantity = 4 }); } public override async Task Watch(StockRequest request, IServerStreamWriter<StockReply> responseStream, ServerCallContext context) { if (request.Id != 1) throw new RpcException(new Status(StatusCode.NotFound, "Unknown sample")); foreach (int quantity in new[] { 4, 3, 2 }) { context.CancellationToken.ThrowIfCancellationRequested(); await responseStream.WriteAsync(new StockReply { Quantity = quantity }); } }}Protos/stock.proto
syntax = "proto3";option csharp_namespace = "Fixture.Contracts";package stock;service StockService { rpc Get (StockRequest) returns (StockReply); rpc Watch (StockRequest) returns (stream StockReply);}message StockRequest { int32 id = 1; }message StockReply { int32 quantity = 1; }Expected result (not executed):
4One typed request produces one typed response.
Read a finite server stream
Dispose the call and enumerate responses to completion.
using Fixture.Contracts;using Grpc.Core;using Grpc.Net.Client;using Microsoft.AspNetCore.Server.Kestrel.Core;using System.Net;var builder = WebApplication.CreateBuilder(args);builder.Logging.ClearProviders();builder.WebHost.ConfigureKestrel(o => o.Listen(IPAddress.Loopback, 0, l => l.Protocols = HttpProtocols.Http2));builder.Services.AddGrpc();await using var app = builder.Build();app.MapGrpcService<StockEndpoint>();using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(timeout.Token);try { using var channel = GrpcChannel.ForAddress(app.Urls.Single()); var client = new StockService.StockServiceClient(channel); var deadline = DateTime.UtcNow.AddSeconds(5);using var call = client.Watch(new StockRequest { Id = 1 }, deadline: deadline, cancellationToken: timeout.Token);await foreach (var item in call.ResponseStream.ReadAllAsync(timeout.Token)) Console.WriteLine(item.Quantity);} finally { await app.StopAsync(); }public class StockEndpoint : StockService.StockServiceBase { public override Task<StockReply> Get(StockRequest request, ServerCallContext context) { if (request.Id != 1) throw new RpcException(new Status(StatusCode.NotFound, "Unknown sample")); return Task.FromResult(new StockReply { Quantity = 4 }); } public override async Task Watch(StockRequest request, IServerStreamWriter<StockReply> responseStream, ServerCallContext context) { if (request.Id != 1) throw new RpcException(new Status(StatusCode.NotFound, "Unknown sample")); foreach (int quantity in new[] { 4, 3, 2 }) { context.CancellationToken.ThrowIfCancellationRequested(); await responseStream.WriteAsync(new StockReply { Quantity = quantity }); } }}Protos/stock.proto
syntax = "proto3";option csharp_namespace = "Fixture.Contracts";package stock;service StockService { rpc Get (StockRequest) returns (StockReply); rpc Watch (StockRequest) returns (stream StockReply);}message StockRequest { int32 id = 1; }message StockReply { int32 quantity = 1; }Expected result (not executed):
432The server sends ordered messages for this single finite call.
Distinguish a missing resource from transport failure
Use the same contract with an unknown fictional ID.
using Fixture.Contracts;using Grpc.Core;using Grpc.Net.Client;using Microsoft.AspNetCore.Server.Kestrel.Core;using System.Net;var builder = WebApplication.CreateBuilder(args);builder.Logging.ClearProviders();builder.WebHost.ConfigureKestrel(o => o.Listen(IPAddress.Loopback, 0, l => l.Protocols = HttpProtocols.Http2));builder.Services.AddGrpc();await using var app = builder.Build();app.MapGrpcService<StockEndpoint>();using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(timeout.Token);try { using var channel = GrpcChannel.ForAddress(app.Urls.Single()); var client = new StockService.StockServiceClient(channel); var deadline = DateTime.UtcNow.AddSeconds(5);try { await client.GetAsync(new StockRequest { Id = 99 }, deadline: deadline, cancellationToken: timeout.Token);} catch (RpcException ex) when (ex.StatusCode == StatusCode.NotFound) { Console.WriteLine(ex.StatusCode);}} finally { await app.StopAsync(); }public class StockEndpoint : StockService.StockServiceBase { public override Task<StockReply> Get(StockRequest request, ServerCallContext context) { if (request.Id != 1) throw new RpcException(new Status(StatusCode.NotFound, "Unknown sample")); return Task.FromResult(new StockReply { Quantity = 4 }); } public override async Task Watch(StockRequest request, IServerStreamWriter<StockReply> responseStream, ServerCallContext context) { if (request.Id != 1) throw new RpcException(new Status(StatusCode.NotFound, "Unknown sample")); foreach (int quantity in new[] { 4, 3, 2 }) { context.CancellationToken.ThrowIfCancellationRequested(); await responseStream.WriteAsync(new StockReply { Quantity = quantity }); } }}Protos/stock.proto
syntax = "proto3";option csharp_namespace = "Fixture.Contracts";package stock;service StockService { rpc Get (StockRequest) returns (StockReply); rpc Watch (StockRequest) returns (stream StockReply);}message StockRequest { int32 id = 1; }message StockReply { int32 quantity = 1; }Expected result (not executed):
NotFoundA missing sample is an application status, not a connectivity diagnosis.
Apply the concept
Extend the contract with an optional warehouse label. Explain how to remove an old field safely and how clients should respond to a deadline exceeded after a write.
Use the manual practice and knowledge check to reason about the boundary. Do not deploy these local demonstrations as production services.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
gRPC contracts and streaming — knowledge check
Apply the lesson concepts to the following scenarios.
What identifies a protobuf field on the wire?
Which method shape has one request and multiple responses?
Does a deadline error prove that a server write never happened?
Which protocol does native ASP.NET Core gRPC require?
Can ordinary browser gRPC-Web clients use every native streaming shape?