.NET › gRPC Services
What is the purpose of the ServerCallContext parameter present in every gRPC server method, and what information does it expose?
BeginnerAnswer
ServerCallContext gives access to call-level metadata and control within a gRPC method implementation: the incoming request metadata (headers), the CancellationToken tied to the call's deadline/cancellation, the peer's identity information, and the ability to write outgoing response headers/trailers -- serving a similar role to HttpContext in a typical ASP.NET Core controller action, but specific to the gRPC call lifecycle.
public override async Task<OrderResponse> GetOrder(GetOrderRequest request, ServerCallContext context) {
var userId = context.GetHttpContext().User.FindFirst("sub")?.Value;
context.CancellationToken.ThrowIfCancellationRequested();
var order = await _repository.GetAsync(request.OrderId, context.CancellationToken);
return MapToResponse(order);
}Real-world example A gRPC service method passes context.CancellationToken through to every downstream async database call, ensuring that if the client cancels or the deadline expires, the entire chain of work is cooperatively cancelled rather than continuing pointlessly after the client has given up.