Search code examples
c#.netgrpc

Add metadata for all calls to gRPC service


How do i add metadata for all calls to a service? I know how to send metadata for a specific call but i cant seem to find how to add standard metadata for all calls.

I tried to use a client interceptor to add the metadata there but don't seem like i can manipulate the headers for the context here.

I'm using gRPC in .net framework, not .net core.


Solution

  • If this is a client call (rather than a server call), you should be able to do this in an interceptor, by overriding the client call - for example:

    public override AsyncClientStreamingCall<TRequest, TResponse> AsyncClientStreamingCall<TRequest, TResponse>(ClientInterceptorContext<TRequest, TResponse> context, AsyncClientStreamingCallContinuation<TRequest, TResponse> continuation)
    {
        Metadata newMetadata = // your logic here
        context = new ClientInterceptorContext<TRequest, TResponse>(context.Method,
            context.Host, context.Options.WithHeaders(newMetadata));
        return base.AsyncClientStreamingCall(context, continuation);
    }
    

    (you'd need to override all 5 client-call methods; AsyncClientStreamingCall, AsyncDuplexStreamingCall, AsyncServerStreamingCall, AsyncUnaryCall and BlockingUnaryCall)