OperationContext Classe

Definição

Fornece acesso ao contexto de execução de um método de serviço.

public ref class OperationContext sealed : System::ServiceModel::IExtensibleObject<System::ServiceModel::OperationContext ^>
public sealed class OperationContext : System.ServiceModel.IExtensibleObject<System.ServiceModel.OperationContext>
type OperationContext = class
    interface IExtensibleObject<OperationContext>
Public NotInheritable Class OperationContext
Implements IExtensibleObject(Of OperationContext)
Herança
OperationContext
Implementações

Exemplos

O exemplo de código a seguir usa a propriedade e GetCallbackChannel o Current método para obter o canal de volta para o chamador de dentro de um método . Todos os métodos neste exemplo são métodos unidirecionais, permitindo que o serviço e o cliente se comuniquem em ambas as direções de forma independente. Nesse caso, o aplicativo cliente de exemplo espera apenas uma chamada de retorno antes de sair, mas outro cliente, por exemplo, um cliente Windows Forms, pode receber qualquer número de chamadas do serviço.

using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.Threading;

namespace Microsoft.WCF.Documentation
{
  [ServiceContract(
    Name = "SampleDuplexHello",
    Namespace = "http://microsoft.wcf.documentation",
    CallbackContract = typeof(IHelloCallbackContract),
    SessionMode = SessionMode.Required
  )]
  public interface IDuplexHello
  {
    [OperationContract(IsOneWay = true)]
    void Hello(string greeting);
  }

  public interface IHelloCallbackContract
  {
    [OperationContract(IsOneWay = true)]
    void Reply(string responseToGreeting);
  }

  public class DuplexHello : IDuplexHello
  {
    public DuplexHello()
    {
      Console.WriteLine("Service object created: " + this.GetHashCode().ToString());
    }

    ~DuplexHello()
    {
      Console.WriteLine("Service object destroyed: " + this.GetHashCode().ToString());
    }

    public void Hello(string greeting)
    {
      Console.WriteLine("Caller sent: " + greeting);
      Console.WriteLine("Session ID: " + OperationContext.Current.SessionId);
      Console.WriteLine("Waiting two seconds before returning call.");
      // Put a slight delay to demonstrate asynchronous behavior on client.
      Thread.Sleep(2000);
      IHelloCallbackContract callerProxy
        = OperationContext.Current.GetCallbackChannel<IHelloCallbackContract>();
      string response = "Service object " + this.GetHashCode().ToString() + " received: " + greeting;
      Console.WriteLine("Sending back: " + response);
      callerProxy.Reply(response);
    }
  }
}


Imports System.Collections.Generic
Imports System.ServiceModel
Imports System.Threading

Namespace Microsoft.WCF.Documentation
    <ServiceContract(Name:="SampleDuplexHello", Namespace:="http://microsoft.wcf.documentation", _
                     CallbackContract:=GetType(IHelloCallbackContract), SessionMode:=SessionMode.Required)> _
  Public Interface IDuplexHello
        <OperationContract(IsOneWay:=True)> _
        Sub Hello(ByVal greeting As String)
    End Interface

  Public Interface IHelloCallbackContract
    <OperationContract(IsOneWay := True)> _
    Sub Reply(ByVal responseToGreeting As String)
  End Interface

  Public Class DuplexHello
      Implements IDuplexHello
    Public Sub New()
      Console.WriteLine("Service object created: " & Me.GetHashCode().ToString())
    End Sub

    Protected Overrides Sub Finalize()
      Console.WriteLine("Service object destroyed: " & Me.GetHashCode().ToString())
    End Sub

    Public Sub Hello(ByVal greeting As String) Implements IDuplexHello.Hello
      Console.WriteLine("Caller sent: " & greeting)
      Console.WriteLine("Session ID: " & OperationContext.Current.SessionId)
      Console.WriteLine("Waiting two seconds before returning call.")
      ' Put a slight delay to demonstrate asynchronous behavior on client.
      Thread.Sleep(2000)
            Dim callerProxy = OperationContext.Current.GetCallbackChannel(Of IHelloCallbackContract)()
            Dim response = "Service object " & Me.GetHashCode().ToString() & " received: " & greeting
      Console.WriteLine("Sending back: " & response)
      callerProxy.Reply(response)
    End Sub
  End Class
End Namespace

O cliente a seguir implementa o SampleDuplexHelloCallback para receber a mensagem de retorno de chamada. O contrato de retorno de chamada importado não é o mesmo nome que o do serviço, devido ao uso da Name propriedade no exemplo anterior. Observe que o cliente não faz nenhuma suposição sobre se ou quando ele pode receber um retorno de chamada; o retorno de chamada do servidor é totalmente independente da chamada de saída do cliente.

Observação

Para obter um exemplo que usa a OperationContext classe em um cenário de cliente, consulte OperationContextScope.

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

namespace Microsoft.WCF.Documentation
{
  public class Client : SampleDuplexHelloCallback
  {
    AutoResetEvent waitHandle;

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

    public void Run()
    {
      // Picks up configuration from the config file.
      SampleDuplexHelloClient wcfClient
        = new SampleDuplexHelloClient(new InstanceContext(this));
      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();
        wcfClient.Close();
      }
      catch (TimeoutException timeProblem)
      {
        Console.WriteLine("The service operation timed out. " + timeProblem.Message);
        Console.ReadLine();
        wcfClient.Abort();
      }
      catch (CommunicationException commProblem)
      {
        Console.WriteLine("There was a communication problem. " + commProblem.Message);
        Console.ReadLine();
        wcfClient.Abort();
      }
    }

    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
  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 config file.
      Dim wcfClient As New SampleDuplexHelloClient(New InstanceContext(Me))
      Try
        Console.ForegroundColor = ConsoleColor.White
        Console.WriteLine("Enter a greeting to send and press ENTER: ")
        Console.Write(">>> ")
        Console.ForegroundColor = ConsoleColor.Green
                Dim greeting = 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()
        wcfClient.Close()
      Catch timeProblem As TimeoutException
        Console.WriteLine("The service operation timed out. " & timeProblem.Message)
        Console.ReadLine()
        wcfClient.Abort()
      Catch commProblem As CommunicationException
        Console.WriteLine("There was a communication problem. " & commProblem.Message)
        Console.ReadLine()
        wcfClient.Abort()
      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

Comentários

Use o OperationContext de dentro de uma operação de serviço para acessar o ambiente de execução da operação atual. Em particular, o contexto de operação é usado para acessar canais de retorno de chamada em serviços duplex, armazenar dados de estado extra entre partes das operações e acessar cabeçalhos e propriedades de mensagens de entrada, bem como adicionar cabeçalhos e propriedades de mensagem de saída.

Para obter mais informações sobre como usar extensões para armazenar dados de estado, consulte Objetos Extensíveis.

O OperationContext tem as seguintes propriedades e métodos.

Construtores

OperationContext(IContextChannel)

Inicializa uma nova instância da classe OperationContext que usa o IContextChannel especificado em um aplicativo cliente.

Propriedades

Channel

Obtém o canal associado ao objeto OperationContext atual.

ClaimsPrincipal

Obtém a entidade de segurança baseada em declarações associada à operação.

Current

Obtém ou define o contexto de execução do thread atual.

EndpointDispatcher

Obtém ou define o dispatcher do ponto de extremidade para o ponto de extremidade a inspecionar ou modificar.

Extensions

Obtém a coleção de extensões de serviço do contexto da mensagem atual.

HasSupportingTokens

Obtém um valor que indica se a mensagem de entrada tem os tokens de suporte.

Host

Obtém o ServiceHost do objeto de serviço atual.

IncomingMessageHeaders

Obtém os cabeçalhos de mensagem de entrada do OperationContext.

IncomingMessageProperties

Obtém as propriedades da mensagem para a mensagem de entrada no OperationContext.

IncomingMessageVersion

Obtém a versão da mensagem SOAP recebida para o OperationContext.

InstanceContext

Obtém o objeto InstanceContext que gerencia a instância de serviço atual.

IsUserContext

Esta propriedade é destinada a uso pelo sistema e não deve ser chamada pelos usuários.

OutgoingMessageHeaders

Obtém os cabeçalhos de mensagem de entrada para o OperationContext ativo.

OutgoingMessageProperties

Obtém as propriedades de mensagem para a mensagem de saída no OperationContext ativo.

RequestContext

Obtém ou define a implementação RequestContext para esse método.

ServiceSecurityContext

Obtém ou define o ServiceSecurityContext em que este método é executado.

SessionId

Obtém o String usado para identificar a sessão atual.

SupportingTokens

Obtém um ICollection<T> do tipo SecurityToken.

Métodos

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.

(Herdado de Object)
GetCallbackChannel<T>()

Obtém um canal para a instância do cliente que chamou a operação atual.

GetHashCode()

Serve como a função de hash padrão.

(Herdado de Object)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
MemberwiseClone()

Cria uma cópia superficial do Object atual.

(Herdado de Object)
SetTransactionComplete()

Confirma a transação em execução no momento.

ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.

(Herdado de Object)

Eventos

OperationCompleted

Ocorre quando a operação foi concluída.

Aplica-se a