Dela via


Ange körningsbeteende för klienten

Windows Communication Foundation-klienter (WCF), till exempel WCF-tjänster (Windows Communication Foundation), kan konfigureras för att ändra körningsbeteendet så att det passar klientprogrammet. Det finns tre attribut för att ange körningsbeteende för klienten. Duplex-klientanropsobjekt kan använda attributen CallbackBehaviorAttribute och CallbackDebugBehavior för att ändra körningsbeteendet. Det andra attributet, ClientViaBehavior, kan användas för att skilja det logiska målet från det omedelbara nätverkets mål. Dessutom kan duplex-klientåteranropstyper använda vissa av beteendena på tjänstsidan. Mer information finns i Ange körningsbeteende för tjänsten.

Använda CallbackBehaviorAttribute

Du kan konfigurera eller utöka körningsbeteendet för en implementering av återanropskontrakt i ett klientprogram med hjälp CallbackBehaviorAttribute av klassen . Det här attributet utför en liknande funktion för motringningsklassen ServiceBehaviorAttribute som klassen, med undantag för instancing-beteende och transaktionsinställningar.

Klassen CallbackBehaviorAttribute måste tillämpas på klassen som implementerar återanropskontraktet. Om det tillämpas på en icke-dubbelsidig kontraktsimplementering utlöses ett InvalidOperationException undantag vid körning. I följande kodexempel visas en CallbackBehaviorAttribute klass för ett motringningsobjekt som använder SynchronizationContext objektet för att fastställa den tråd som ska konverteras till, ValidateMustUnderstand egenskapen för att framtvinga meddelandeverifiering och IncludeExceptionDetailInFaults egenskapen för att returnera undantag som FaultException objekt till tjänsten i felsökningssyfte.

using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Threading;

namespace Microsoft.WCF.Documentation
{
  [CallbackBehaviorAttribute(
   IncludeExceptionDetailInFaults= true,
    UseSynchronizationContext=true,
    ValidateMustUnderstand=true
  )]
  public class Client : SampleDuplexHelloCallback
  {
    AutoResetEvent waitHandle;

    public Client()
    {
      waitHandle = new AutoResetEvent(false);
    }

    public void Run()
    {
      // Picks up configuration from the configuration file.
      SampleDuplexHelloClient wcfClient
        = new SampleDuplexHelloClient(new InstanceContext(this), "WSDualHttpBinding_SampleDuplexHello");
      try
      {
        Console.ForegroundColor = ConsoleColor.White;
        Console.WriteLine("Enter a greeting to send and press ENTER: ");
        Console.Write(">>> ");
        Console.ForegroundColor = ConsoleColor.Green;
        string greeting = Console.ReadLine();
        Console.ForegroundColor = ConsoleColor.White;
        Console.WriteLine("Called service with: \r\n\t" + greeting);
        wcfClient.Hello(greeting);
        Console.WriteLine("Execution passes service call and moves to the WaitHandle.");
        this.waitHandle.WaitOne();
        Console.ForegroundColor = ConsoleColor.Blue;
        Console.WriteLine("Set was called.");
        Console.Write("Press ");
        Console.ForegroundColor = ConsoleColor.Red;
        Console.Write("ENTER");
        Console.ForegroundColor = ConsoleColor.Blue;
        Console.Write(" to exit...");
        Console.ReadLine();
      }
      catch (TimeoutException timeProblem)
      {
        Console.WriteLine("The service operation timed out. " + timeProblem.Message);
        Console.ReadLine();
      }
      catch (CommunicationException commProblem)
      {
        Console.WriteLine("There was a communication problem. " + commProblem.Message);
        Console.ReadLine();
      }
    }
    public static void Main()
    {
      Client client = new Client();
      client.Run();
    }

    public void Reply(string response)
    {
      Console.WriteLine("Received output.");
      Console.WriteLine("\r\n\t" + response);
      this.waitHandle.Set();
    }
  }
}

Imports System.ServiceModel
Imports System.ServiceModel.Channels
Imports System.Threading

Namespace Microsoft.WCF.Documentation
    <CallbackBehaviorAttribute(IncludeExceptionDetailInFaults:=True, UseSynchronizationContext:=True, ValidateMustUnderstand:=True)> _
    Public Class Client
        Implements SampleDuplexHelloCallback
        Private waitHandle As AutoResetEvent

        Public Sub New()
            waitHandle = New AutoResetEvent(False)
        End Sub

        Public Sub Run()
            ' Picks up configuration from the configuration file.
            Dim wcfClient As New SampleDuplexHelloClient(New InstanceContext(Me), "WSDualHttpBinding_SampleDuplexHello")
            Try
                Console.ForegroundColor = ConsoleColor.White
                Console.WriteLine("Enter a greeting to send and press ENTER: ")
                Console.Write(">>> ")
                Console.ForegroundColor = ConsoleColor.Green
                Dim greeting As String = Console.ReadLine()
                Console.ForegroundColor = ConsoleColor.White
                Console.WriteLine("Called service with: " & Constants.vbCrLf & Constants.vbTab & greeting)
                wcfClient.Hello(greeting)
                Console.WriteLine("Execution passes service call and moves to the WaitHandle.")
                Me.waitHandle.WaitOne()
                Console.ForegroundColor = ConsoleColor.Blue
                Console.WriteLine("Set was called.")
                Console.Write("Press ")
                Console.ForegroundColor = ConsoleColor.Red
                Console.Write("ENTER")
                Console.ForegroundColor = ConsoleColor.Blue
                Console.Write(" to exit...")
                Console.ReadLine()
            Catch timeProblem As TimeoutException
                Console.WriteLine("The service operation timed out. " & timeProblem.Message)
                Console.ReadLine()
            Catch commProblem As CommunicationException
                Console.WriteLine("There was a communication problem. " & commProblem.Message)
                Console.ReadLine()
            End Try
        End Sub
        Public Shared Sub Main()
            Dim client As New Client()
            client.Run()
        End Sub

        Public Sub Reply(ByVal response As String) Implements SampleDuplexHelloCallback.Reply
            Console.WriteLine("Received output.")
            Console.WriteLine(Constants.vbCrLf & Constants.vbTab & response)
            Me.waitHandle.Set()
        End Sub
    End Class
End Namespace

Använda CallbackDebugBehavior för att aktivera flödet av hanterad undantagsinformation

Du kan aktivera flödet av hanterad undantagsinformation i ett klientåteranropsobjekt tillbaka till tjänsten i felsökningssyfte genom att ange IncludeExceptionDetailInFaults egenskapen till true antingen programmatiskt eller från en programkonfigurationsfil.

Att returnera hanterad undantagsinformation till tjänster kan vara en säkerhetsrisk eftersom undantagsinformation visar information om den interna klientimplementering som obehöriga tjänster kan använda. Även om CallbackDebugBehavior egenskaperna också kan ställas in programmatiskt kan det vara lätt att glömma att inaktivera IncludeExceptionDetailInFaults när du distribuerar.

På grund av de säkerhetsproblem som är inblandade rekommenderar vi starkt att:

  • Du använder en programkonfigurationsfil för att ange värdet för IncludeExceptionDetailInFaults egenskapen till true.

  • Du gör det bara i kontrollerade felsökningsscenarier.

I följande kodexempel visas en klientkonfigurationsfil som instruerar WCF att returnera hanterad undantagsinformation från ett klientanropsobjekt i SOAP-meddelanden.

  <client>
      <endpoint 
        address="http://localhost:8080/DuplexHello" 
        binding="wsDualHttpBinding"
        bindingConfiguration="WSDualHttpBinding_SampleDuplexHello"
        contract="SampleDuplexHello" 
        name="WSDualHttpBinding_SampleDuplexHello"
        behaviorConfiguration="enableCallbackDebug">
      </endpoint>
  </client>
<behaviors>
  <endpointBehaviors>
    <behavior name="enableCallbackDebug">
      <callbackDebug includeExceptionDetailInFaults="true"/>
    </behavior>
  </endpointBehaviors>
</behaviors>

Använda ClientViaBehavior-beteendet

Du kan använda beteendet ClientViaBehavior för att ange den enhetliga resursidentifierare som transportkanalen ska skapas för. Använd det här beteendet när det omedelbara nätverkets mål inte är den avsedda processorn för meddelandet. Detta möjliggör konversationer med flera hopp när det anropande programmet inte nödvändigtvis känner till det slutliga målet eller när målrubriken Via inte är en adress.

Se även