OperationContext Classe
Définition
Important
Certaines informations portent sur la préversion du produit qui est susceptible d’être en grande partie modifiée avant sa publication. Microsoft exclut toute garantie, expresse ou implicite, concernant les informations fournies ici.
Fournit l’accès au contexte d’exécution d’une méthode de service.
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)
- Héritage
-
OperationContext
- Implémente
Exemples
L’exemple de code suivant utilise la propriété et GetCallbackChannel la Current méthode pour récupérer le canal à l’appelant à partir d’une méthode. Toutes les méthodes de cet exemple sont des méthodes unidirectionnelle, ce qui permet au service et au client de communiquer indépendamment dans les deux sens. Dans ce cas, l’exemple d’application cliente attend un seul appel de retour avant de quitter, mais un autre client, par exemple un client Windows Forms, peut recevoir n’importe quel nombre d’appels du 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
Le client suivant implémente le SampleDuplexHelloCallback message de rappel pour recevoir le message de rappel. Le contrat de rappel importé n’est pas le même nom que celui du service, en raison de l’utilisation de la Name propriété dans l’exemple précédent. Notez que le client ne fait aucune hypothèse quant à la réception ou non d’un rappel ; le rappel de serveur est entièrement indépendant de l’appel sortant du client.
Note
Pour obtenir un exemple qui utilise la OperationContext classe dans un scénario client, consultez 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
Remarques
Utilisez l’élément OperationContext à partir d’une opération de service pour accéder à l’environnement d’exécution de l’opération en cours. En particulier, le contexte d’opération est utilisé pour accéder aux canaux de rappel dans les services duplex, pour stocker des données d’état supplémentaires dans des parties des opérations, et pour accéder aux en-têtes et propriétés de message entrants, ainsi qu’à ajouter des en-têtes de message sortants et des propriétés.
Pour plus d’informations sur l’utilisation d’extensions pour stocker des données d’état, consultez Extensible Objects.
Les OperationContext propriétés et méthodes suivantes sont disponibles.
La Current propriété retourne l’objet OperationContext représentant le contexte d’exécution actuel.
La ServiceSecurityContext propriété retourne l’environnement de sécurité sous lequel la méthode s’exécute.
La EndpointDispatcher propriété obtient l’opération System.ServiceModel.Dispatcher.EndpointDispatcher.
La Extensions propriété retourne une collection d’extensions pour le fichier actif OperationContext.
La Host propriété retourne l’objet ServiceHostBase qui gère le service.
La HasSupportingTokens propriété retourne une valeur qui indique si la méthode a des jetons de prise en charge, le cas échéant, la SupportingTokens propriété les obtient.
Les IncomingMessageHeaderspropriétés et IncomingMessageVersion les IncomingMessagePropertiespropriétés obtiennent ces éléments à partir du message entrant.
L’événement OperationCompleted est déclenché lorsque l’opération est terminée.
Les OutgoingMessageHeaders propriétés obtiennent OutgoingMessageProperties ces éléments pour le message sortant.
La RequestContext propriété retourne l’implémentation RequestContext de la méthode.
La InstanceContext propriété retourne l’associé InstanceContext à l’opération.
La SessionId propriété retourne l’identificateur de session pour le canal et l’objet actuels.
La GetCallbackChannel méthode retourne un canal de rappel à l’appelant dans le cas d’une communication duplex.
La SetTransactionComplete méthode valide la transaction actuelle.
Constructeurs
| Nom | Description |
|---|---|
| OperationContext(IContextChannel) |
Initialise une nouvelle instance de la OperationContext classe qui utilise le spécifié dans une application cliente IContextChannel . |
Propriétés
| Nom | Description |
|---|---|
| Channel |
Obtient le canal associé à l’objet actuel OperationContext . |
| ClaimsPrincipal |
Obtient le principal basé sur les revendications associé à l’opération. |
| Current |
Obtient ou définit le contexte d’exécution du thread actuel. |
| EndpointDispatcher |
Obtient ou définit le répartiteur de point de terminaison pour le point de terminaison à inspecter ou modifier. |
| Extensions |
Obtient la collection d’extensions de service à partir du contexte de message actuel. |
| HasSupportingTokens |
Obtient une valeur qui indique si le message entrant a des jetons de prise en charge. |
| Host |
Obtient l’objet ServiceHost de service actuel. |
| IncomingMessageHeaders |
Obtient les en-têtes de message entrants pour le OperationContext. |
| IncomingMessageProperties |
Obtient les propriétés du message entrant dans le OperationContext. |
| IncomingMessageVersion |
Obtient la version du message SOAP entrant pour le OperationContext. |
| InstanceContext |
Obtient l’objet InstanceContext qui gère l’instance de service actuelle. |
| IsUserContext |
Cette propriété est destinée à une utilisation système et ne doit pas être appelée par les utilisateurs. |
| OutgoingMessageHeaders |
Obtient les en-têtes de message sortants pour l’actif OperationContext. |
| OutgoingMessageProperties |
Obtient les propriétés du message sortant dans le message actif OperationContext. |
| RequestContext |
Obtient ou définit l’implémentation RequestContext de cette méthode. |
| ServiceSecurityContext |
Obtient ou définit le ServiceSecurityContext contenu dans lequel cette méthode s’exécute. |
| SessionId |
Obtient l’élément String utilisé pour identifier la session active. |
| SupportingTokens |
Obtient un ICollection<T> type SecurityToken. |
Méthodes
| Nom | Description |
|---|---|
| Equals(Object) |
Détermine si l’objet spécifié est égal à l’objet actuel. (Hérité de Object) |
| GetCallbackChannel<T>() |
Obtient un canal vers l’instance cliente qui a appelé l’opération actuelle. |
| GetHashCode() |
Sert de fonction de hachage par défaut. (Hérité de Object) |
| GetType() |
Obtient la Type de l’instance actuelle. (Hérité de Object) |
| MemberwiseClone() |
Crée une copie superficielle du Objectactuel. (Hérité de Object) |
| SetTransactionComplete() |
Valide la transaction en cours d’exécution. |
| ToString() |
Retourne une chaîne qui représente l’objet actuel. (Hérité de Object) |
Événements
| Nom | Description |
|---|---|
| OperationCompleted |
Se produit lorsque l’opération est terminée. |