schh
schh

Reputation: 391

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.

Upvotes: 4

Views: 5324

Answers (2)

AlexeySRG
AlexeySRG

Reputation: 861

More elegant solution for the client (valid for all requests):

var channel = new Grpc.Core.Channel("localhost", 5001, ssl);
var invoker = channel.Intercept(m => { m.Add("my-custom-header", "my value 123"); return m; });
var client = new Greeter.GreeterClient(invoker);

Upvotes: 4

Marc Gravell
Marc Gravell

Reputation: 1062865

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)

Upvotes: 4

Related Questions