Настройка поведений клиентов

Windows Communication Foundation (WCF) настраивает поведение двумя способами: путем ссылки на конфигурации поведения, определенные в <behavior> разделе файла конфигурации клиентского приложения или программно в вызывающем приложении. В этом разделе описываются оба подхода.

При использовании файла конфигурации конфигурация поведения представляет собой именованную коллекцию параметров конфигурации. Имя каждой из конфигураций поведения должно быть уникальным. Эта строка используется в атрибуте behaviorConfiguration конфигурации конечной точки, чтобы связать конечную точку с поведением.

Пример 1

В следующем фрагменте кода конфигурации определяется поведение с именем myBehavior. Конечная точка клиента ссылается на это поведение в атрибуте behaviorConfiguration.

<configuration>  
    <system.serviceModel>  
        <behaviors>  
            <endpointBehaviors>  
                <behavior name="myBehavior">  
                    <clientVia />  
                </behavior>  
            </endpointBehaviors>  
        </behaviors>  
        <bindings>  
            <basicHttpBinding>  
                <binding name="myBinding" maxReceivedMessageSize="10000" />  
            </basicHttpBinding>  
        </bindings>  
        <client>  
            <endpoint address="myAddress" binding="basicHttpBinding" bindingConfiguration="myBinding" behaviorConfiguration="myBehavior" contract="myContract" />  
        </client>  
    </system.serviceModel>  
</configuration>  

Управление поведениями программным образом

Вы также можете настроить или вставить поведение программным способом, найдя соответствующее Behaviors свойство в клиентском объекте Windows Communication Foundation (WCF) или на объекте фабрики клиентских каналов перед открытием клиента.

Пример 2

В следующем примере кода показано, как программным образом вставить поведение, обратившись к свойству Behaviors объекта ServiceEndpoint, возвращаемого свойством Endpoint до создания объекта канала.

public class Client
{
  public static void Main()
  {
    try
    {
      // Picks up configuration from the config file.
      ChannelFactory<ISampleServiceChannel> factory
        = new ChannelFactory<ISampleServiceChannel>("WSHttpBinding_ISampleService");

      // Add the client side behavior programmatically to all created channels.
      factory.Endpoint.Behaviors.Add(new EndpointBehaviorMessageInspector());

      ISampleServiceChannel wcfClientChannel = factory.CreateChannel();

      // Making calls.
      Console.WriteLine("Enter the greeting to send: ");
      string greeting = Console.ReadLine();
      Console.WriteLine("The service responded: " + wcfClientChannel.SampleMethod(greeting));

      Console.WriteLine("Press ENTER to exit:");
      Console.ReadLine();

      // Done with service.
      wcfClientChannel.Close();
      Console.WriteLine("Done!");
    }
    catch (TimeoutException timeProblem)
    {
      Console.WriteLine("The service operation timed out. " + timeProblem.Message);
      Console.Read();
    }
    catch (FaultException<SampleFault> fault)
    {
      Console.WriteLine("SampleFault fault occurred: {0}", fault.Detail.FaultMessage);
      Console.Read();
    }
    catch (CommunicationException commProblem)
    {
      Console.WriteLine("There was a communication problem. " + commProblem.Message);
      Console.Read();
    }
  }
Public Class Client
    Public Shared Sub Main()
        Try
            ' Picks up configuration from the config file.
            Dim factory As New ChannelFactory(Of ISampleServiceChannel)("WSHttpBinding_ISampleService")

            ' Add the client side behavior programmatically to all created channels.
            factory.Endpoint.Behaviors.Add(New EndpointBehaviorMessageInspector())

            Dim wcfClientChannel As ISampleServiceChannel = factory.CreateChannel()

            ' Making calls.
            Console.WriteLine("Enter the greeting to send: ")
            Dim greeting As String = Console.ReadLine()
            Console.WriteLine("The service responded: " & wcfClientChannel.SampleMethod(greeting))

            Console.WriteLine("Press ENTER to exit:")
            Console.ReadLine()

            ' Done with service. 
            wcfClientChannel.Close()
            Console.WriteLine("Done!")
        Catch timeProblem As TimeoutException
            Console.WriteLine("The service operation timed out. " & timeProblem.Message)
            Console.Read()
        Catch fault As FaultException(Of SampleFault)
            Console.WriteLine("SampleFault fault occurred: {0}", fault.Detail.FaultMessage)
            Console.Read()
        Catch commProblem As CommunicationException
            Console.WriteLine("There was a communication problem. " & commProblem.Message)
            Console.Read()
        End Try
    End Sub

См. также