IDispatchMessageInspector Interface

Definição

Define os métodos que permitem a inspeção ou modificação personalizada de mensagens do aplicativo de entrada e saída em aplicativos de serviço.Defines the methods that enable custom inspection or modification of inbound and outbound application messages in service applications.

public interface class IDispatchMessageInspector
public interface IDispatchMessageInspector
type IDispatchMessageInspector = interface
Public Interface IDispatchMessageInspector

Exemplos

O exemplo de código a seguir mostra IDispatchMessageInspector um básico que grava uma cadeia de caracteres no console do quando ele é invocado.The following code example shows a basic IDispatchMessageInspector that writes a string to the console when it is invoked.

#region IDispatchMessageInspector Members
public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, IClientChannel channel, InstanceContext instanceContext)
{
  Console.WriteLine("IDispatchMessageInspector.AfterReceiveRequest called.");
  return null;
}

public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
{
  Console.WriteLine("IDispatchMessageInspector.BeforeSendReply called.");
}
#endregion
#Region "IDispatchMessageInspector Members"
    Public Function AfterReceiveRequest(ByRef request As System.ServiceModel.Channels.Message, _
                       ByVal channel As IClientChannel, ByVal instanceContext As InstanceContext) _
                       As Object Implements IDispatchMessageInspector.AfterReceiveRequest
        Console.WriteLine("IDispatchMessageInspector.AfterReceiveRequest called.")
        Return Nothing
    End Function

    Public Sub BeforeSendReply(ByRef reply As System.ServiceModel.Channels.Message, ByVal correlationState As Object) _
    Implements IDispatchMessageInspector.BeforeSendReply
        Console.WriteLine("IDispatchMessageInspector.BeforeSendReply called.")
    End Sub
#End Region

O exemplo de código a seguir mostra a implementação IServiceBehavior de um que Inspector adiciona o DispatchRuntime.MessageInspectors IDispatchMessageInspector à coleção.The following code example shows the implementation of an IServiceBehavior that adds the InspectorIDispatchMessageInspector to the DispatchRuntime.MessageInspectors collection.

#region IServiceBehavior Members
public void AddBindingParameters(
  ServiceDescription serviceDescription, 
  ServiceHostBase serviceHostBase, 
  System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, 
  BindingParameterCollection bindingParameters
)
{ return; }

public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
  foreach (ChannelDispatcher chDisp in serviceHostBase.ChannelDispatchers)
  {
    foreach (EndpointDispatcher epDisp in chDisp.Endpoints)
    {
      epDisp.DispatchRuntime.MessageInspectors.Add(new Inspector());
      foreach (DispatchOperation op in epDisp.DispatchRuntime.Operations)
        op.ParameterInspectors.Add(new Inspector());
    }
  }
}
#Region "IServiceBehavior Members"
    Public Sub AddBindingParameters(ByVal serviceDescription As ServiceDescription, _
                   ByVal serviceHostBase As ServiceHostBase, ByVal endpoints As  _
                   System.Collections.ObjectModel.Collection(Of ServiceEndpoint), _
                   ByVal bindingParameters As BindingParameterCollection) Implements IServiceBehavior.AddBindingParameters
        Return
    End Sub

    Public Sub ApplyDispatchBehavior(ByVal serviceDescription As ServiceDescription, _
                                     ByVal serviceHostBase As ServiceHostBase) Implements _
                                     IServiceBehavior.ApplyDispatchBehavior
        For Each chDisp As ChannelDispatcher In serviceHostBase.ChannelDispatchers
            For Each epDisp As EndpointDispatcher In chDisp.Endpoints
                epDisp.DispatchRuntime.MessageInspectors.Add(New Inspector())
                For Each op As DispatchOperation In epDisp.DispatchRuntime.Operations
                    op.ParameterInspectors.Add(New Inspector())
                Next op
            Next epDisp
        Next chDisp
    End Sub

O exemplo de código a seguir mostra o uso de um arquivo de configuração de aplicativo para carregar o comportamento Inspectordo serviço que insere o IDispatchMessageInspector.The following code example shows the use of an application configuration file to load the service behavior that inserts the InspectorIDispatchMessageInspector.

<configuration>
  <system.serviceModel>
    <services>
      <service 
        name="Microsoft.WCF.Documentation.SampleService"
        behaviorConfiguration="metadataSupport">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8080/SampleService" />
          </baseAddresses>
        </host>
        <endpoint
          address=""
          binding="wsHttpBinding"
          contract="Microsoft.WCF.Documentation.ISampleService"
        />
        <endpoint
           address="mex"
           binding="mexHttpBinding"
           contract="IMetadataExchange"
        />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="metadataSupport">
          <serviceMetadata httpGetEnabled="true" httpGetUrl=""/>
          <serviceInterceptors />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <extensions>
      <behaviorExtensions>
        <add 
          name="serviceInterceptors" 
          type="Microsoft.WCF.Documentation.InspectorInserter, HostApplication, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"
        />
      </behaviorExtensions>
    </extensions>
  </system.serviceModel>
</configuration>

Comentários

Implemente IDispatchMessageInspector para inspecionar ou modificar mensagens de aplicativo de entrada ou saída antes de expedir uma mensagem de solicitação para uma operação ou antes de retornar uma mensagem de resposta a um chamador.Implement IDispatchMessageInspector to inspect or modify inbound or outbound application messages either prior to dispatching a request message to an operation or before returning a reply message to a caller. Há um grande número de cenários que exigem a interceptação de mensagens antes de invocar a operação para a qual ela está destinada.There are a large number of scenarios that require intercepting messages prior to invoking the operation for which it is destined. Por exemplo, você pode registrar mensagens de aplicativo de entrada ou executar algum recurso com base em um cabeçalho de mensagem.For example, you can log incoming application messages or perform some feature based on a message header.

Normalmente, os inspetores de mensagem são inseridos porSystem.ServiceModel.Description.IServiceBehaviorum comportamento de serviço ()System.ServiceModel.Description.IEndpointBehavior, um comportamento de ponto de extremidadeSystem.ServiceModel.Description.IContractBehavior() ou um comportamento de contrato ().Typically, message inspectors are inserted by a service behavior (System.ServiceModel.Description.IServiceBehavior), an endpoint behavior (System.ServiceModel.Description.IEndpointBehavior), or a contract behavior (System.ServiceModel.Description.IContractBehavior). O comportamento, em seguida, adiciona o Inspetor DispatchRuntime.MessageInspectors de mensagem à coleção.The behavior then adds the message inspector to the DispatchRuntime.MessageInspectors collection. Para obter mais informações sobre como estender o tempo de execução usando comportamentos, consulte estendendo ServiceHost e a camada do modelo de serviço.For more information about extending the runtime using behaviors, see Extending ServiceHost and the Service Model Layer.

  • O AfterReceiveRequest método habilita o comportamento personalizado depois de receber a mensagem, mas antes de expedir para a operação pretendida.The AfterReceiveRequest method enables custom behavior after receiving the message but before dispatching it to the intended operation.

  • O BeforeSendReply método habilita o comportamento personalizado depois que a operação retorna, mas antes de a resposta ser enviada.The BeforeSendReply method enables custom behavior after the operation returns but before the reply is sent.

Observação

IDispatchMessageInspectoros objetos são sempre chamados no mesmo ponto durante a expedição da mensagem, independentemente de uma operação ser unidirecional ou de solicitação-resposta.IDispatchMessageInspector objects are always called at the same point during message dispatch regardless of whether an operation is one-way or request-reply.

Métodos

AfterReceiveRequest(Message, IClientChannel, InstanceContext)

Chamado depois que uma mensagem de entrada tiver sido recebida, mas antes ela foi enviada para a operação pretendida.Called after an inbound message has been received but before the message is dispatched to the intended operation.

BeforeSendReply(Message, Object)

Chamado depois que a operação foi retornada, mas antes que a mensagem de resposta seja enviada.Called after the operation has returned but before the reply message is sent.

Aplica-se a