客户端拦截:
public class ClientLoggerInterceptor : Interceptor
{
public override AsyncUnaryCall<TResponse> AsyncUnaryCall<TRequest, TResponse>(
TRequest request,
ClientInterceptorContext<TRequest, TResponse> context,
AsyncUnaryCallContinuation<TRequest, TResponse> continuation)
{
var requestStr = request.ToString();
var requestMethod = context.Method;
var response = continuation(request, context);
return response;
}
public override AsyncServerStreamingCall<TResponse> AsyncServerStreamingCall<TRequest, TResponse>(TRequest request, ClientInterceptorContext<TRequest, TResponse> context, AsyncServerStreamingCallContinuation<TRequest, TResponse> continuation)
{
var requestStr = request.ToString();
var requestMethod = context.Method;
var call = base.AsyncServerStreamingCall(request, context, continuation);
return call;
}
}
客户端拦截器注册:
services.AddGrpcClient<T>(options =>
{
options.InterceptorRegistrations.Add(new Grpc.Net.ClientFactory.InterceptorRegistration(InterceptorScope.Client, s => new ClientLoggerInterceptor()));
});
服务端:
public class ServerLoggerInterceptor: Interceptor
{
public override Task<TResponse> UnaryServerHandler<TRequest, TResponse>(
TRequest request,
ServerCallContext context,
UnaryServerMethod<TRequest, TResponse> continuation)
{
var requestStr = request.ToString();
var requestMethod = context.Method;
var response = continuation(request, context);
return response;
}
}