Search code examples
wcfloggingconfigurationcommunicationinspector

Switch from IClientMessageInspector to IParameterInspector?


My winform WCF client have a custom IEndpointBehavior where the ApplyClientBehavior method looks like this :

public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
        {
            clientRuntime.MessageInspectors.Add(new CustomMessageInspector());
            clientRuntime.CallbackDispatchRuntime.MessageInspectors.Add(new CustomMessageInspector());      
        }

To get hold of the serlized parameters I have changed from IClientMessageInspector and IDispatchMessageInspector to IParameterInspector. How to I convert the IEndpointBehavior to load this IParameterInspector instead?

I have found this :

SimpleServiceClient proxy = new SimpleServiceClient();
proxy.Endpoint.Contract.Operations[0].Behaviors.Add(new MyParameterInspector());

My client is however created from CreateChannel so Behaviors do not exists, instead there is a OperationsBehaviors that will not take a IParameterInspector.


Solution

  • You can configure its behavior in the configuration file,Here is a demo:

              public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
            foreach (ClientOperation op in clientRuntime.Operations)
                op.ParameterInspectors.Add(new Inspector());
        }
    

    This is ApplyClientBehavior.

        public class Inspector : IParameterInspector
    {
        public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState)
        {
            Console.WriteLine(
                    "IParameterInspector.AfterCall called for {0} with return value {1}.",
                         operationName,
                        returnValue.ToString()
                        );
        }
    
        public object BeforeCall(string operationName, object[] inputs)
        {
            Console.WriteLine("IParameterInspector.BeforeCall called for {0}.", operationName);
            return null;
        }
    }
    

    The Inspector implements the interface of IParameterInspector.

                <behaviors>
            <endpointBehaviors>
                <behavior name="Test">
                    <clientInterceptors/>
                </behavior>
            </endpointBehaviors>
        </behaviors>
        <extensions>
            <behaviorExtensions>
                <add
                  name="clientInterceptors"
                  type="Client.InspectorInserter,Client, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" />
            </behaviorExtensions>
        </extensions>
    

    This is the configuration file.

    enter image description here

    This is the result of the client-side running.

    Here is the reference link:

    https://learn.microsoft.com/en-us/dotnet/framework/wcf/extending/how-to-inspect-or-modify-parameters