Advertisement
Advanced ASP.NET Core, gRPC Services

What are gRPC interceptors, and how do they compare to ASP.NET Core middleware or MVC filters for implementing cross-cutting concerns?

Short answer

gRPC interceptors (implementing Interceptor, overriding methods like UnaryServerHandler) wrap RPC call execution on either the server or client side, serving a conceptually similar cross-cutting role to middleware/filters but specific to the gRPC pipeline -- used for logging…

Save ASP.NET Core mock interview
Advertisement
AModel answer
gRPC interceptors (implementing Interceptor, overriding methods like UnaryServerHandler) wrap RPC call execution on either the server or client side, serving a conceptually similar cross-cutting role to middleware/filters but specific to the gRPC pipeline -- used for logging, authentication token extraction, exception translation, or metrics collection uniformly across all gRPC service methods, registered via AddGrpc(options => options.Interceptors.Add<MyInterceptor>()) for server-side or on the channel for client-side.
public class LoggingInterceptor : Interceptor {
    public override async Task<TResponse> UnaryServerHandler<TRequest, TResponse>(
        TRequest request, ServerCallContext context, UnaryServerMethod<TRequest, TResponse> continuation) {
        var start = DateTime.UtcNow;
        try {
            return await continuation(request, context);
        } finally {
            Console.WriteLine($"{context.Method} took {(DateTime.UtcNow - start).TotalMilliseconds}ms");
        }
    }
}

builder.Services.AddGrpc(options => options.Interceptors.Add<LoggingInterceptor>());
Real-world example
A gRPC service applies a single logging interceptor globally to record execution time and status for every RPC method across the entire service, avoiding the need to add manual timing code to each individual method implementation.
Likely follow-ups
  • How do interceptors differ in scope/capability between server-side and client-side registration?
  • How would you chain multiple interceptors and control their execution order?
Related topics