Практическое руководство. Проверка или изменение сообщений на клиенте

Вы можете проверить или изменить входящие или исходящие сообщения через клиент WCF, реализовав System.ServiceModel.Dispatcher.IClientMessageInspector и вставив его в среду выполнения клиента. Дополнительные сведения см. в разделе "Расширение клиентов". Эквивалентную функцию в службе выполняет интерфейс System.ServiceModel.Dispatcher.IDispatchMessageInspector. Полный пример кода см. в примере инспекторов сообщений.

Проверка или изменение сообщений

  1. Реализуйте интерфейс System.ServiceModel.Dispatcher.IClientMessageInspector.

  2. Реализуйте интерфейс System.ServiceModel.Description.IEndpointBehavior или System.ServiceModel.Description.IContractBehavior в зависимости от области, в которую нужно вставить инспектор сообщений клиентов. System.ServiceModel.Description.IEndpointBehavior позволяет изменить поведение на уровне конечной точки. System.ServiceModel.Description.IContractBehavior позволяет изменить поведение на уровне контракта.

  3. Вставьте поведение до вызова метода ClientBase<TChannel>.Open или метода ICommunicationObject.Open фабрики каналов System.ServiceModel.ChannelFactory<TChannel>. Дополнительные сведения см. в разделе "Настройка и расширение среды выполнения с помощью поведения".

Пример

В следующих примерах кода показаны, по порядку:

  • реализация инспектора клиента;

  • поведение конечной точки, вставляющее инспектор;

  • Класс BehaviorExtensionElement - это производный класс, позволяющий добавить поведение в файл конфигурации.

  • Файл конфигурации, добавляющий поведение конечной точки, которая вставляет пользовательский инспектор сообщений в среду выполнения клиента.

// Client message inspector  
public class SimpleMessageInspector : IClientMessageInspector  
{  
    public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)  
    {  
        // Implement this method to inspect/modify messages after a message  
        // is received but prior to passing it back to the client
        Console.WriteLine("AfterReceiveReply called");  
    }  
  
    public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, IClientChannel channel)  
    {  
        // Implement this method to inspect/modify messages before they
        // are sent to the service  
        Console.WriteLine("BeforeSendRequest called");  
        return null;  
    }  
}  
// Endpoint behavior  
public class SimpleEndpointBehavior : IEndpointBehavior  
{  
    public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)  
    {  
         // No implementation necessary  
    }  
  
    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)  
    {  
        clientRuntime.MessageInspectors.Add(new SimpleMessageInspector());  
    }  
  
    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)  
    {  
         // No implementation necessary  
    }  
  
    public void Validate(ServiceEndpoint endpoint)  
    {  
         // No implementation necessary  
    }  
}  
// Configuration element
public class SimpleBehaviorExtensionElement : BehaviorExtensionElement  
{  
    public override Type BehaviorType  
    {  
        get { return typeof(SimpleEndpointBehavior); }  
    }  
  
    protected override object CreateBehavior()  
    {  
         // Create the  endpoint behavior that will insert the message  
         // inspector into the client runtime  
        return new SimpleEndpointBehavior();  
    }  
}  
<?xml version="1.0" encoding="utf-8" ?>  
<configuration>  
    <system.serviceModel>  
        <client>  
            <endpoint address="http://localhost:8080/SimpleService/"
                      binding="wsHttpBinding"
                      behaviorConfiguration="clientInspectorsAdded"
                      contract="ServiceReference1.IService1"  
                      name="WSHttpBinding_IService1"/>  
        </client>  
  
      <behaviors>  
        <endpointBehaviors>  
          <behavior name="clientInspectorsAdded">  
            <simpleBehaviorExtension />  
          </behavior>  
        </endpointBehaviors>  
      </behaviors>  
      <extensions>  
        <behaviorExtensions>  
          <add  
            name="simpleBehaviorExtension"  
            type="SimpleServiceLib.SimpleBehaviorExtensionElement, Host, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"/>  
        </behaviorExtensions>  
      </extensions>  
    </system.serviceModel>  
</configuration>  

См. также