OperationContext Clase
Definición
Proporciona acceso al contexto de ejecución de un método de servicio.Provides access to the execution context of a service method.
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)
- Herencia
-
OperationContext
- Implementaciones
Ejemplos
En el ejemplo de código siguiente Current se usa la propiedad y el GetCallbackChannel método para volver a obtener el canal al autor de la llamada desde un método.The following code example uses the Current property and GetCallbackChannel method to obtain the channel back to the caller from within a method. Todos los métodos en este ejemplo son unidireccionales, lo que permite que el servicio y el cliente se comuniquen en ambas direcciones de manera independiente.All methods in this example are one-way methods, enabling the service and the client to communicate in both directions independently. En este caso, la aplicación cliente de ejemplo espera sólo una llamada de devolución antes de salir, pero otro cliente; por ejemplo, un cliente de Windows Forms, puede recibir cualquier número de llamadas desde el servicio.In this case, the example client application expects only one return call before it exits, but another client, for example a Windows Forms client, can receive any number of calls from the service.
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
El siguiente cliente implementa SampleDuplexHelloCallback
para recibir el mensaje de devolución de llamada.The following client implements the SampleDuplexHelloCallback
to receive the callback message. El contrato de devolución de llamada importado no es el mismo nombre que el del servicio, debido al uso de la Name propiedad en el ejemplo anterior.The imported callback contract is not the same name as the one in the service, due to the use of the Name property in the preceding example. Observe que el cliente no hace ninguna suposición sobre si podría recibir una devolución de llamada o cuándo; la devolución de llamada del servidor es completamente independiente de la llamada saliente del cliente.Note that the client makes no assumptions about whether or when it might receive a callback; the server callback is entirely independent of the client's outbound call.
Nota
Para obtener un ejemplo en el que se usa la OperationContext clase en un escenario de cliente, vea OperationContextScope .For an example that uses the OperationContext class in a client scenario, see 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
Comentarios
Utilice OperationContext desde una operación de servicio para tener acceso al entorno de ejecución de la operación actual.Use the OperationContext from within a service operation to access the current operation execution environment. En particular, el contexto de la operación se utiliza para tener acceso a los canales de devolución de llamada en servicios dúplex, almacenar datos de estado adicionales en partes de las operaciones, y para tener acceso a los encabezados de mensaje entrante y propiedades así como agregar encabezados de mensajes salientes y propiedades.In particular, the operation context is used to access callback channels in duplex services, to store extra state data across portions of the operations, and to access incoming message headers and properties as well as add outgoing message headers and properties.
Para obtener más información sobre el uso de extensiones para almacenar datos de estado, vea objetos extensibles.For more information about using extensions to store state data, see Extensible Objects.
OperationContextTiene las siguientes propiedades y métodos.The OperationContext has the following properties and methods.
La Current propiedad devuelve el OperationContext objeto que representa el contexto de ejecución actual.The Current property returns the OperationContext object representing the current execution context.
La ServiceSecurityContext propiedad devuelve el entorno de seguridad en el que se ejecuta el método.The ServiceSecurityContext property returns the security environment under which the method executes.
La EndpointDispatcher propiedad obtiene el de la operación System.ServiceModel.Dispatcher.EndpointDispatcher .The EndpointDispatcher property gets the operation's System.ServiceModel.Dispatcher.EndpointDispatcher.
La Extensions propiedad devuelve una colección de extensiones para el actual OperationContext .The Extensions property returns an extension collection for the current OperationContext.
La Host propiedad devuelve el ServiceHostBase objeto que administra el servicio.The Host property returns the ServiceHostBase object that manages the service.
La HasSupportingTokens propiedad devuelve un valor que indica si el método tiene tokens auxiliares, si es así, la SupportingTokens propiedad los obtiene.The HasSupportingTokens property returns a value that indicates whether the method has supporting tokens, if so, the SupportingTokens property gets them.
Las IncomingMessageHeaders IncomingMessageProperties propiedades, y IncomingMessageVersion obtienen estos elementos del mensaje entrante.The IncomingMessageHeaders, IncomingMessageProperties, and IncomingMessageVersion properties get these items from the incoming message.
El OperationCompleted evento se desencadena cuando se ha completado la operación.The OperationCompleted event is fired when the operation has completed.
Las OutgoingMessageHeaders OutgoingMessageProperties propiedades y obtienen estos elementos para el mensaje saliente.The OutgoingMessageHeaders and OutgoingMessageProperties properties get these items for the outbound message.
La RequestContext propiedad devuelve la RequestContext implementación para el método.The RequestContext property returns the RequestContext implementation for the method.
La InstanceContext propiedad devuelve el InstanceContext asociado a la operación.The InstanceContext property returns the InstanceContext associated with the operation.
La SessionId propiedad devuelve el identificador de la sesión para el canal y el objeto actuales.The SessionId property returns the session identifier for the current channel and object.
El GetCallbackChannel método devuelve un canal de devolución de llamada al llamador en el caso de la comunicación dúplex.The GetCallbackChannel method returns a callback channel to the caller in the case of duplex communication.
El SetTransactionComplete método confirma la transacción actual.The SetTransactionComplete method commits the current transaction.
Constructores
OperationContext(IContextChannel) |
Inicializa una nueva instancia de la clase OperationContext que usa el IContextChannel especificado en una aplicación cliente.Initializes a new instance of the OperationContext class that uses the specified IContextChannel in a client application. |
Propiedades
Channel |
Obtiene el canal asociado con el objeto OperationContext actual.Gets the channel associated with the current OperationContext object. |
ClaimsPrincipal |
Obtiene la entidad de seguridad basada en notificaciones asociada con la operación.Gets the claims-based principal associated with the operation. |
Current |
Obtiene o define el contexto de ejecución del subproceso actual.Gets or sets the execution context for the current thread. |
EndpointDispatcher |
Obtiene o establece el distribuidor del extremo para el extremo que se vaya a inspeccionar o modificar.Gets or sets the endpoint dispatcher for the endpoint to inspect or modify. |
Extensions |
Recibe la colección de extensiones de servicio desde el contexto del mensaje actual.Gets the collection of service extensions from the current message context. |
HasSupportingTokens |
Obtiene un valor que indica si el mensaje entrante tiene tokens auxiliares.Gets a value that indicates whether the incoming message has supporting tokens. |
Host |
Obtiene ServiceHost para el objeto de servicio actual.Gets the ServiceHost for the current service object. |
IncomingMessageHeaders |
Obtiene los encabezados de mensaje entrante para OperationContext.Gets the incoming message headers for the OperationContext. |
IncomingMessageProperties |
Obtiene las propiedades de mensaje para el mensaje entrante en OperationContext.Gets the message properties for the incoming message in the OperationContext. |
IncomingMessageVersion |
Obtiene la versión del mensaje SOAP entrante para OperationContext.Gets the incoming SOAP message version for the OperationContext. |
InstanceContext |
Obtiene el objeto InstanceContext que administra la instancia del servicio actual.Gets the InstanceContext object that manages the current service instance. |
IsUserContext |
Esta propiedad está pensada para su uso por el sistema y los usuarios no deberían recurrir a ella.This property is intended for system use and should not be called by users. |
OutgoingMessageHeaders |
Obtiene los encabezados de mensajes salientes para el OperationContext activo.Gets the outgoing message headers for the active OperationContext. |
OutgoingMessageProperties |
Obtiene las propiedades del mensaje para el mensaje saliente en el OperationContext activo.Gets the message properties for the outbound message in the active OperationContext. |
RequestContext |
Obtiene o define la implementación de RequestContext para este método.Gets or sets the RequestContext implementation for this method. |
ServiceSecurityContext |
Obtiene o define ServiceSecurityContext dentro del cual se ejecuta este método.Gets or sets the ServiceSecurityContext within which this method executes. |
SessionId |
Obtiene el String utilizado para identificar la sesión actual.Gets the String used to identify the current session. |
SupportingTokens |
Obtiene un ICollection<T> de tipo SecurityToken.Gets a ICollection<T> of type SecurityToken. |
Métodos
Equals(Object) |
Determina si el objeto especificado es igual que el objeto actual.Determines whether the specified object is equal to the current object. (Heredado de Object) |
GetCallbackChannel<T>() |
Obtiene un canal a la instancia del cliente que haya llamado a la operación actual.Gets a channel to the client instance that called the current operation. |
GetHashCode() |
Sirve como la función hash predeterminada.Serves as the default hash function. (Heredado de Object) |
GetType() |
Obtiene el Type de la instancia actual.Gets the Type of the current instance. (Heredado de Object) |
MemberwiseClone() |
Crea una copia superficial del Object actual.Creates a shallow copy of the current Object. (Heredado de Object) |
SetTransactionComplete() |
Confirma la transacción que se está ejecutando actualmente.Commits the currently executing transaction. |
ToString() |
Devuelve una cadena que representa el objeto actual.Returns a string that represents the current object. (Heredado de Object) |
Eventos
OperationCompleted |
Se produce cuando se ha completado la operación.Occurs when the operation has completed. |