Condividi tramite


OperationContextScope

Nell'esempio OperationContextScope viene illustrato come inviare informazioni aggiuntive su una chiamata Windows Communication Foundation (WCF) utilizzando le intestazioni. In questo esempio sia il server che il client sono applicazioni console.

Aa395196.note(it-it,VS.100).gifNota:
La procedura di installazione e le istruzioni di compilazione per questo esempio si trovano alla fine dell'argomento.

Nell'esempio viene illustrato in che modo un client può inviare informazioni aggiuntive come un MessageHeader utilizzando OperationContextScope. Un oggetto OperationContextScope viene creato definendone l'ambito su un canale. Le intestazioni che devono essere tradotte nel servizio remoto possono essere aggiunte alla raccolta OutgoingMessageHeaders. Le intestazioni aggiunte alla raccolta possono essere recuperate nel servizio accedendo alla proprietà IncomingMessageHeaders. Le chiamate a questa proprietà vengono effettuate sui più canali e quindi le intestazioni aggiunte al client possono essere applicate solo al canale utilizzato per creare OperationContextScope.

MessageHeaderReader

Si tratta del servizio di esempio che riceve un messaggio dal client e tenta di cercare l'intestazione nella raccolta IncomingMessageHeaders. Il client passa il GUID inviato nell'intestazione, quindi il servizio recupera l'intestazione personalizzata e, se presente, lo confronta con il GUID passato come argomento dal client.

public bool RetrieveHeader(string guid)
{
     MessageHeaders messageHeaderCollection = 
             OperationContext.Current.IncomingMessageHeaders;
     String guidHeader = null;

     Console.WriteLine("Trying to check if IncomingMessageHeader " +
               " collection contains header with value {0}", guid);
     if (messageHeaderCollection.FindHeader(
                       CustomHeader.HeaderName, 
                       CustomHeader.HeaderNamespace) != -1)
     {
          guidHeader = messageHeaderCollection.GetHeader<String>(
           CustomHeader.HeaderName, CustomHeader.HeaderNamespace);
     }
     else
     {
          Console.WriteLine("No header was found");
     }
     if (guidHeader != null)
     {
          Console.WriteLine("Found header with value {0}. "+ 
         "Does it match with GUID sent as parameter: {1}", 
          guidHeader, guidHeader.Equals(guid));
      }

      Console.WriteLine();
      //Return true if header is present and equals the guid sent by
      // client as argument
      return (guidHeader != null && guidHeader.Equals(guid));
}

MessageHeaderClient

Si tratta dell'implementazione client che utilizza il proxy generato da Strumento ServiceModel Metadata Utility Tool (Svcutil.exe) per comunicare con il servizio remoto. Crea innanzitutto due oggetti proxy di MessageHeaderReaderClient.

//Create two clients to the remote service.
MessageHeaderReaderClient client1 = new MessageHeaderReaderClient();
MessageHeaderReaderClient client2 = new MessageHeaderReaderClient();

Il client crea quindi un OperationContextScope e ne definisce l'ambito su client1. Aggiunge un MessageHeader a OutgoingMessageHeaders ed esegue una chiamata su entrambi i client. Verifica che l'intestazione venga inviata solo su client1 e non su client2 controllando il valore restituito dalla chiamata RetrieveHeader.

using (new OperationContextScope(client1.InnerChannel))
{
    //Create a new GUID that is sent as the header.
    String guid = Guid.NewGuid().ToString();

    //Create a MessageHeader for the GUID we just created.
    MessageHeader customHeader = MessageHeader.CreateHeader(CustomHeader.HeaderName, CustomHeader.HeaderNamespace, guid);

    //Add the header to the OutgoingMessageHeader collection.
    OperationContext.Current.OutgoingMessageHeaders.Add(customHeader);

    //Now call RetreieveHeader on both the proxies. Since the OperationContextScope is tied to 
    //client1's InnerChannel, the header should only be added to calls made on that client.
    //Calls made on client2 should not be sending the header across even though the call
    //is made in the same OperationContextScope.
    Console.WriteLine("Using client1 to send message");
    Console.WriteLine("Did server retrieve the header? : Actual: {0}, Expected: True", client1.RetrieveHeader(guid));

    Console.WriteLine();
    Console.WriteLine("Using client2 to send message");
    Console.WriteLine("Did server retrieve the header? : Actual: {0}, Expected: False", client2.RetrieveHeader(guid));
}

Questo esempio è indipendente. L'esecuzione dell'esempio fornisce l'output di esempio seguente:

Prompt> Service.exe
The service is ready.
Press <ENTER> to terminate service.

Trying to check if IncomingMessageHeader collection contains header with value 2239da67-546f-42d4-89dc-8eb3c06215d8
Found header with value 2239da67-546f-42d4-89dc-8eb3c06215d8. Does it match with GUID sent as parameter: True

Trying to check if IncomingMessageHeader collection contains header with value 2239da67-546f-42d4-89dc-8eb3c06215d8
No header was found


Prompt>Client.exe
Using client1 to send message
Did server retrieve the header? : Actual: True, Expected: True

Using client2 to send message
Did server retrieve the header? : Actual: False, Expected: False

Press <ENTER> to terminate client.

Per impostare, compilare ed eseguire l'esempio

  1. Assicurarsi di aver eseguito Procedura di installazione singola per gli esempi di Windows Communication Foundation.

  2. Per compilare l'edizione in C# o Visual Basic .NET della soluzione, seguire le istruzioni in Generazione degli esempi Windows Communication Foundation.

  3. Per eseguire l'esempio in una configurazione con un solo computer o tra computer diversi, seguire le istruzioni in Running the Windows Communication Foundation Samples.

Aa395196.Important(it-it,VS.100).gif Nota:
È possibile che gli esempi siano già installati nel computer. Verificare la directory seguente (impostazione predefinita) prima di continuare.

<UnitàInstallazione>:\WF_WCF_Samples

Se questa directory non esiste, andare alla pagina relativa agli esempi di Windows Communication Foundation (WCF) e Windows Workflow Foundation (WF) per .NET Framework 4 per scaricare tutti gli esempi di Windows Communication Foundation (WCF) e WF. Questo esempio si trova nella directory seguente.

<UnitàInstallazione>:\WF_WCF_Samples\WCF\Basic\Services\OperationContextScope