In ASP.NET Core gRPC, how do you write and register a server interceptor, and how does it differ from ASP.NET Core middleware?
answer
- derive from Grpc.Core.Interceptors.Interceptor
- override UnaryServerHandler and friends
- Interceptors.Add<T>() in AddGrpc
- AddServiceOptions<TService> for one service
- created per call unless registered in DI
basics
~10 sDerive from Interceptor, override UnaryServerHandler (and the streaming handlers you need), and register it with AddGrpc(o => o.Interceptors.Add<T>()) or AddServiceOptions<TService>. Unlike middleware it runs only for gRPC calls and sees typed messages and ServerCallContext.
solid answer
~40 sA server interceptor derives from `Interceptor` and overrides `UnaryServerHandler<TRequest, TResponse>(request, context, continuation)`; calling `await continuation(request, context)` runs the next interceptor or the service method. Streaming calls go through `ServerStreamingServerHandler`, `ClientStreamingServerHandler` and `DuplexStreamingServerHandler`, so an interceptor that overrides only the unary handler never sees streams. Register it for every service with `builder.Services.AddGrpc(o => o.Interceptors.Add<QuoteAuditInterceptor>())`, or for one service with `.AddServiceOptions<PriceQuoteService>(o => o.Interceptors.Add<...>())`; global interceptors wrap service-specific ones. By default an interceptor is created per call with constructor injection and disposed afterwards; registering the type in DI makes the container's lifetime apply. Middleware runs earlier, for every HTTP request, sees only `HttpContext` and bytes; an interceptor runs inside the gRPC pipeline with the deserialized message, the method name and `ServerCallContext`.
code
csharp · 21 linespublic sealed class QuoteAuditInterceptor(ILogger<QuoteAuditInterceptor> logger) : Interceptor
{
public override async Task<TResponse> UnaryServerHandler<TRequest, TResponse>(
TRequest request, ServerCallContext context,
UnaryServerMethod<TRequest, TResponse> continuation)
{
var started = Stopwatch.GetTimestamp();
try
{
return await continuation(request, context);
}
finally
{
logger.LogInformation("{Method} took {Elapsed}", context.Method,
Stopwatch.GetElapsedTime(started));
}
}
}
// Program.cs
builder.Services.AddGrpc(o => o.Interceptors.Add<QuoteAuditInterceptor>());go deeper
Recall that an interceptor derives from Interceptor, overrides a handler and calls continuation, and is registered in AddGrpc options.
Explain global versus per-service registration, the resulting order, the per-call lifetime and which handler wraps which call shape.
Decide what belongs in middleware and what in interceptors, keep interceptors from swallowing errors, and cover streaming handlers as well as unary.
Set a consistent cross-cutting policy for many gRPC services so auditing, validation and metrics are applied once and owned clearly.
## The Interceptor base class `Grpc.Core.Interceptors.Interceptor` (in `Grpc.Core.Api`) has one virtual method per call shape and side. The server-side ones are: | Method | Wraps | |---|---| | `UnaryServerHandler` | unary calls | | `ServerStreamingServerHandler` | server-streaming calls | | `ClientStreamingServerHandler` | client-streaming calls | | `DuplexStreamingServerHandler` | bidirectional calls | The client-side counterparts, such as `AsyncUnaryCall` and `BlockingUnaryCall`, are used on channels and client-factory clients, not on the server. Each server handler receives the request (or stream), the `ServerCallContext` and a `continuation` delegate. Code before `await continuation(...)` runs before the service method; code after it sees the response or the exception. ## Registering interceptors - **Global:** `builder.Services.AddGrpc(options => options.Interceptors.Add<QuoteAuditInterceptor>());` applies to every gRPC service in the app. - **One service:** `builder.Services.AddGrpc().AddServiceOptions<PriceQuoteService>(options => options.Interceptors.Add<TenantInterceptor>());`. - `Interceptors.Add<T>(params object[] args)` can pass constructor arguments that DI cannot supply. **Order:** the options are merged so that global interceptors come first and service-specific ones after them; within one collection, registration order applies. The first interceptor in the list is the outermost: it sees the request first and the result last. ## Lifetime When a call starts, the activator asks the request's service provider for the interceptor type: 1. If the type is registered in DI (and no explicit arguments were given), that instance is used with the registered lifetime and is not disposed by gRPC. 2. Otherwise a new instance is created for the call with constructor injection, and it is disposed when the call ends. So by default an interceptor is **per call**, and it can depend on scoped services such as a `DbContext` or a tenant accessor. Registering it as a singleton is possible, but then it must not capture scoped services. ## Interceptor or middleware? | Concern | ASP.NET Core middleware | gRPC server interceptor | |---|---|---| | Runs for | every HTTP request that reaches it | gRPC calls only | | Sees | `HttpContext`, raw request body | typed request and response messages, `ServerCallContext` | | Position | before endpoint execution | inside the gRPC call, around the service method | | Typical use | authentication, CORS, logging of HTTP traffic | per-method auditing, validation of messages, metrics by rpc name | | Failure signal | HTTP status code | gRPC status through `RpcException` | For the price-quote service, authentication stays in middleware (`UseAuthentication`, `[Authorize]` or `RequireAuthorization()` on the mapped service), while an interceptor records which symbol each caller requested and how long the method took, keyed by `context.Method`. ## Pitfalls - Overriding only `UnaryServerHandler` and expecting the streaming quote feed to be audited too. - Catching every exception and returning a default response, which turns failures into successes; rethrow, or convert to `RpcException` with the right status. - Doing blocking I/O before `continuation`, which delays every call; keep the code asynchronous. ## Where interceptors sit relative to authorization Authorization for gRPC endpoints is evaluated by the authorization middleware before the endpoint runs, so a caller rejected by `[Authorize]` or `RequireAuthorization()` never reaches any interceptor. Interceptors therefore see only calls that were already allowed, which makes them a poor place for access control and a good place for per-method concerns: - validating message contents that depend on the rpc, such as a maximum basket size; - adding tags or metrics keyed by `context.Method`; - translating domain exceptions into `RpcException` with a consistent status. Because an interceptor is plain C#, it can be unit-tested by calling `UnaryServerHandler` with a fake `continuation` delegate and a test `ServerCallContext`.
- Your interceptor needs a scoped ITenantContext. Is constructor injection safe?Yes, as long as you do not register the interceptor as a singleton. With the default activation it is created per call from the request's service provider, so scoped dependencies resolve for that call and the interceptor is disposed afterwards. A singleton registration would capture one scope's instance for the app's lifetime.
- How do you add an interceptor to outgoing calls made with a client-factory client?On the `IHttpClientBuilder` returned by `AddGrpcClient<T>()`, call `.AddInterceptor<T>()`, optionally with `InterceptorScope.Client` so the interceptor is created per client instance instead of per channel. Client interceptors override the client-side methods such as `AsyncUnaryCall`.
- Overriding UnaryServerHandler also intercepts server-streaming calls.
- Service-specific interceptors run before the global ones registered in AddGrpc.
- Interceptors are always singletons, so they cannot use scoped services.
- A gRPC interceptor runs for every HTTP request, including static files and health probes.
- ASP.NET Core middleware can read the deserialized gRPC request message.