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 seguinte utiliza a propriedade e Current o GetCallbackChannel método para obter o canal de volta ao chamador a partir de dentro de um método. Todos os métodos neste exemplo são unidirecionais, permitindo que o serviço e o cliente comuniquem em ambas as direções de forma independente. Neste caso, a aplicação 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 seguinte implementa a SampleDuplexHelloCallback mensagem para receber a chamada de retorno. O contrato de callback importado não tem o mesmo nome do do serviço, devido à utilização da Name propriedade no exemplo anterior. Note-se que o cliente não faz suposições sobre se ou quando poderá receber uma chamada de retorno; O callback do servidor é totalmente independente da chamada de saída do cliente.

Note

Para um exemplo que utiliza a OperationContext classe num cenário cliente, veja 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

Observações

Use o OperationContext a partir de dentro de uma operação de serviço para aceder ao ambiente atual de execução da operação. Em particular, o contexto operacional é usado para aceder a canais de callback em serviços duplex, armazenar dados de estado extra em partes das operações, aceder aos cabeçalhos e propriedades das mensagens recebidas, bem como adicionar cabeçalhos e propriedades das mensagens de saída.

Para mais informações sobre o uso de extensões para armazenar dados de estado, veja Objetos Extensíveis.

O OperationContext possui as seguintes propriedades e métodos.

Construtores

Name Description
OperationContext(IContextChannel)

Inicializa uma nova instância da OperationContext classe que utiliza o especificado IContextChannel numa aplicação cliente.

Propriedades

Name Description
Channel

Obtém o canal associado ao objeto atual OperationContext .

ClaimsPrincipal

Obtém o principal baseado em sinistros associado à operação.

Current

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

EndpointDispatcher

Obtém ou define o despachante do endpoint para o endpoint inspecionar ou modificar.

Extensions

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

HasSupportingTokens

Recebe um valor que indica se a mensagem recebida tem tokens de suporte.

Host

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

IncomingMessageHeaders

Recebe os cabeçalhos das mensagens recebidas para o OperationContextarquivo .

IncomingMessageProperties

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

IncomingMessageVersion

Recebe a versão da mensagem SOAP recebida para o OperationContext.

InstanceContext

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

IsUserContext

Esta propriedade destina-se ao uso do sistema e não deve ser chamada pelos utilizadores.

OutgoingMessageHeaders

Obtém os cabeçalhos das mensagens de saída para o ativo OperationContext.

OutgoingMessageProperties

Obtém as propriedades da mensagem de saída na ativa OperationContext.

RequestContext

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

ServiceSecurityContext

Obtém ou define dentro do ServiceSecurityContext qual este método é executado.

SessionId

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

SupportingTokens

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

Métodos

Name Description
Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.

(Herdado de Object)
GetCallbackChannel<T>()

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

GetHashCode()

Serve como função de hash predefinida.

(Herdado de Object)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
MemberwiseClone()

Cria uma cópia superficial do atual Object.

(Herdado de Object)
SetTransactionComplete()

Faz commit da transação em execução.

ToString()

Devolve uma cadeia que representa o objeto atual.

(Herdado de Object)

evento

Name Description
OperationCompleted

Ocorre quando a operação está concluída.

Aplica-se a