skip to content

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%

answer

  1. IServerStreamWriter<T>.WriteAsync
  2. IAsyncStreamReader<T> with ReadAllAsync
  3. one write at a time
  4. context.CancellationToken and Deadline
  5. context.GetHttpContext()

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.

solid answer

~30 s

For `rpc StreamQuotes (QuoteSubscription) returns (stream QuoteReply)` the base class declares `Task StreamQuotes(QuoteSubscription request, IServerStreamWriter<QuoteReply> responseStream, ServerCallContext context)`. You loop, `await responseStream.WriteAsync(reply)` for each quote, and return when `context.CancellationToken` is cancelled; returning ends the stream. Writes must not overlap: a second `WriteAsync` while one is pending throws `InvalidOperationException`, and so does writing after the call completed. Client streaming gives you an `IAsyncStreamReader<T>`, read with `await foreach (var m in requestStream.ReadAllAsync(ct))`; bidirectional streaming gives both. `ServerCallContext` exposes `CancellationToken`, `Deadline` (`DateTime.MaxValue` when the client set none), `RequestHeaders`, `ResponseTrailers`, `Status`, `Peer` and `WriteResponseHeadersAsync`; `context.GetHttpContext()` reaches `User` and other ASP.NET Core features.

code

csharp · 13 lines
csharp
public override async Task StreamQuotes(QuoteSubscription request,
    IServerStreamWriter<QuoteReply> responseStream, ServerCallContext context)
{
    var user = context.GetHttpContext().User.Identity?.Name;
    logger.LogInformation("{User} subscribed to {Symbol}", user, request.Symbol);

    await foreach (var price in book.WatchAsync(request.Symbol, context.CancellationToken))
    {
        await responseStream.WriteAsync(
            new QuoteReply { Symbol = request.Symbol, Price = price },
            context.CancellationToken);              // one write at a time
    }
}

go deeper

for a junior

Recall the generated signature for a server-streaming method and that returning from it ends the stream.

for a middle

Explain the single-writer rule, reading client streams with ReadAllAsync, and which ServerCallContext members carry cancellation, deadline and metadata.

for a senior

Build long-lived streams that stop promptly on cancellation, funnel concurrent producers safely, and expose the caller's identity through GetHttpContext.

for a principal

Weigh long-lived streams against polling for capacity and connection limits, and set standards for cancellation in every handler.

## Generated signatures Grpc.Tools turns each rpc into a virtual method whose shape depends on which side streams: | rpc shape | Override signature (server) | |---|---| | unary | `Task<TRes> M(TReq request, ServerCallContext context)` | | server streaming | `Task M(TReq request, IServerStreamWriter<TRes> responseStream, ServerCallContext context)` | | client streaming | `Task<TRes> M(IAsyncStreamReader<TReq> requestStream, ServerCallContext context)` | | bidirectional | `Task M(IAsyncStreamReader<TReq> requestStream, IServerStreamWriter<TRes> responseStream, ServerCallContext context)` | When the method's `Task` completes, the call completes: for streaming responses that is the end of the stream, followed by the status and trailers. ## Writing a server stream The price-quote service pushes a new quote for a symbol whenever it changes: 1. Read the subscription from `request`. 2. Loop until `context.CancellationToken` is cancelled, which happens when the client cancels, disconnects or its deadline passes. 3. `await responseStream.WriteAsync(reply)` for every message, or the overload taking a `CancellationToken`. 4. Return to complete the call. Rules the writer enforces: - **One write at a time.** Starting a write while the previous one is still pending throws `InvalidOperationException` ("the previous write is in progress"). If several producers feed one stream, funnel them through a `Channel<T>` and write from a single loop. - **No writes after completion.** Writing after the method returned, or after the request was aborted, throws `InvalidOperationException`. - `responseStream.WriteOptions` can set per-message flags such as `WriteFlags.NoCompress`. ## Reading a client stream `IAsyncStreamReader<T>` has `MoveNext(CancellationToken)` and `Current`. The `ReadAllAsync` extension wraps both as an `IAsyncEnumerable<T>`, so `await foreach (var tick in requestStream.ReadAllAsync(context.CancellationToken))` is the usual form. The loop ends when the client finishes sending. ## What ServerCallContext carries | Member | Use | |---|---| | `CancellationToken` | pass to every async call so work stops with the call | | `Deadline` | the client's deadline as UTC `DateTime`; `DateTime.MaxValue` when none was sent | | `RequestHeaders` | incoming metadata, a `Metadata` collection | | `ResponseTrailers` | metadata sent after the last message | | `Status` | set it to choose the final status without throwing | | `WriteResponseHeadersAsync(Metadata)` | send response headers before the first message | | `Peer`, `Method`, `Host` | caller address and the called method | | `AuthContext` | transport-level identity, such as a client certificate | In ASP.NET Core, `context.GetHttpContext()` (from `Grpc.AspNetCore.Server`) returns the underlying `HttpContext`, so `context.GetHttpContext().User` holds the principal that authentication produced, and request features are available. ## Errors Throw `RpcException` with a `Status` such as `StatusCode.InvalidArgument` for an unknown symbol. An unhandled exception becomes `StatusCode.Unknown` with a generic message unless `EnableDetailedErrors` is on. Which status code fits which failure is protocol design rather than ASP.NET Core. ## Production habits for long-lived streams A quote feed can stay open for hours, so the handler is effectively a small background loop tied to one caller: 1. **Always pass the token.** Every `await` inside the loop takes `context.CancellationToken`; otherwise a disconnected dashboard keeps a loop running until the next price change. 2. **Treat `OperationCanceledException` as normal.** When the token fires mid-write the exception ends the method; it is the expected way out, not an error worth logging as one. 3. **Do not block between writes.** A synchronous wait holds a thread-pool thread per subscriber; await an async source such as a `Channel<T>` reader instead. 4. **Bound per-call memory.** If producers outpace a slow reader, use a bounded channel so the backlog cannot grow without limit. These are what separate a demo stream from one that survives many subscribers.

  • Two background tasks both call responseStream.WriteAsync for the same call. What goes wrong and what is the fix?
    The writer allows one pending write; the second call throws `InvalidOperationException` because the previous write is in progress. Send messages from a single loop instead, for example by having the producers write into a `Channel<QuoteReply>` and having the handler read the channel and call `WriteAsync` sequentially.
  • How do you return metadata alongside the final status of a call?
    Add entries to `context.ResponseTrailers` before the method returns; they are sent with the status after the last message. Headers that must arrive before the first message go through `context.WriteResponseHeadersAsync(metadata)`, which can be called once, before writing.

  • WriteAsync can be called from several tasks at once because the writer is thread-safe.
  • A server-streaming handler must call a Complete method or the stream never ends.
  • ServerCallContext.Deadline is null when the client set no deadline.
  • context.AuthContext holds the ASP.NET Core ClaimsPrincipal from JWT authentication.
  • Writing to the response stream after the handler returned is a safe way to send late updates.