OperationContext OperationContext OperationContext OperationContext Class

定义

提供对服务方法的执行上下文的访问权限。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)
继承
OperationContextOperationContextOperationContextOperationContext
实现

示例

下面的代码示例使用 Current 属性和 GetCallbackChannel 方法获取从方法中返回调用方的通道。The following code example uses the Current property and GetCallbackChannel method to obtain the channel back to the caller from within a method. 此示例中的所有方法都是单向方法,使服务和客户端能够独立地进行双向通信。All methods in this example are one-way methods, enabling the service and the client to communicate in both directions independently. 在此情况下,示例客户端应用程序在退出前仅需要一次返回调用,但其他客户端(例如 Windows 窗体客户端)可以接收来自服务的任意数量的调用。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
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

下列客户端实现 SampleDuplexHelloCallback 以接收回调消息。The following client implements the SampleDuplexHelloCallback to receive the callback message. 由于使用了前面示例中的 Name 属性,导入的回调协定与服务中的回调协定具有不同的名称。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. 请注意,客户端不对其是否或何时可能收到回调作出任何假设;服务器回调与客户端的出站调用完全无关。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.

备注

有关在客户端方案中使用 OperationContext 类的示例,请参见 OperationContextScopeFor 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 Microsoft.VisualBasic
Imports System
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

注解

使用服务操作中的 OperationContext 访问当前操作执行环境。Use the OperationContext from within a service operation to access the current operation execution environment. 特别是,操作上下文用于访问双工服务中的回调通道、存储整个操作部分的额外状态数据、访问传入消息头和属性以及添加传出消息头和属性。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.

有关使用扩展存储状态数据的详细信息,请参阅可扩展对象For more information about using extensions to store state data, see Extensible Objects.

OperationContext 具有以下属性和方法。The OperationContext has the following properties and methods.

构造函数

OperationContext(IContextChannel) OperationContext(IContextChannel) OperationContext(IContextChannel) OperationContext(IContextChannel)

初始化 OperationContext 类的新实例,该类使用客户端应用程序中指定的 IContextChannelInitializes a new instance of the OperationContext class that uses the specified IContextChannel in a client application.

属性

Channel Channel Channel Channel

获取与当前 OperationContext 对象关联的通道。Gets the channel associated with the current OperationContext object.

ClaimsPrincipal ClaimsPrincipal ClaimsPrincipal ClaimsPrincipal

获取与此操作关联的基于声明的主体。Gets the claims-based principal associated with the operation.

Current Current Current Current

获取或设置当前线程的执行上下文。Gets or sets the execution context for the current thread.

EndpointDispatcher EndpointDispatcher EndpointDispatcher EndpointDispatcher

获取或设置要检查或修改的终结点的终结点调度程序。Gets or sets the endpoint dispatcher for the endpoint to inspect or modify.

Extensions Extensions Extensions Extensions

从当前消息上下文中获取服务扩展集合。Gets the collection of service extensions from the current message context.

HasSupportingTokens HasSupportingTokens HasSupportingTokens HasSupportingTokens

获取一个值,该值指示传入消息是否具有支持令牌。Gets a value that indicates whether the incoming message has supporting tokens.

Host Host Host Host

获取当前服务对象的 ServiceHostGets the ServiceHost for the current service object.

IncomingMessageHeaders IncomingMessageHeaders IncomingMessageHeaders IncomingMessageHeaders

获取 OperationContext 的传入消息头。Gets the incoming message headers for the OperationContext.

IncomingMessageProperties IncomingMessageProperties IncomingMessageProperties IncomingMessageProperties

获取 OperationContext 中的传入消息的消息属性。Gets the message properties for the incoming message in the OperationContext.

IncomingMessageVersion IncomingMessageVersion IncomingMessageVersion IncomingMessageVersion

获取 OperationContext 的传入 SOAP 消息版本。Gets the incoming SOAP message version for the OperationContext.

InstanceContext InstanceContext InstanceContext InstanceContext

获取管理当前服务实例的 InstanceContext 对象。Gets the InstanceContext object that manages the current service instance.

IsUserContext IsUserContext IsUserContext IsUserContext

此属性专供系统使用,不应由用户调用。This property is intended for system use and should not be called by users.

OutgoingMessageHeaders OutgoingMessageHeaders OutgoingMessageHeaders OutgoingMessageHeaders

获取活动 OperationContext 的传出消息头。Gets the outgoing message headers for the active OperationContext.

OutgoingMessageProperties OutgoingMessageProperties OutgoingMessageProperties OutgoingMessageProperties

获取活动 OperationContext 中的出站消息的消息属性。Gets the message properties for the outbound message in the active OperationContext.

RequestContext RequestContext RequestContext RequestContext

获取或设置此方法的 RequestContext 实现。Gets or sets the RequestContext implementation for this method.

ServiceSecurityContext ServiceSecurityContext ServiceSecurityContext ServiceSecurityContext

获取或设置将在其中执行此方法的 ServiceSecurityContextGets or sets the ServiceSecurityContext within which this method executes.

SessionId SessionId SessionId SessionId

获取用于标识当前会话的 StringGets the String used to identify the current session.

SupportingTokens SupportingTokens SupportingTokens SupportingTokens

获取一个 ICollection<T> 类型的 SecurityTokenGets a ICollection<T> of type SecurityToken.

方法

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetCallbackChannel<T>() GetCallbackChannel<T>() GetCallbackChannel<T>() GetCallbackChannel<T>()

获取调用当前操作的客户端实例的通道。Gets a channel to the client instance that called the current operation.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

获取当前实例的 TypeGets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(Inherited from Object)
SetTransactionComplete() SetTransactionComplete() SetTransactionComplete() SetTransactionComplete()

提交当前正在执行的事务。Commits the currently executing transaction.

ToString() ToString() ToString() ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(Inherited from Object)

事件

OperationCompleted OperationCompleted OperationCompleted OperationCompleted

操作完成时发生。Occurs when the operation has completed.

适用于