OperationContext 类

定义

提供对服务方法的执行上下文的访问。

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)
继承
OperationContext
实现

示例

下面的代码示例使用 Current 属性和 GetCallbackChannel 方法从 方法内获取回调用方通道。 此示例中的所有方法都是单向方法,使服务和客户端能够独立地进行双向通信。 在这种情况下,示例客户端应用程序在退出前只需要一次返回调用,但另一个客户端(例如Windows 窗体客户端)可以从服务接收任意数量的调用。

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

以下客户端实现 以 SampleDuplexHelloCallback 接收回调消息。 由于在前面的示例中使用了 Name 属性,导入的回调协定与服务中的回调协定的名称不同。 请注意,客户端不对其是否或何时可能收到回调作出任何假设;服务器回调与客户端的出站调用完全无关。

注意

有关在客户端方案中使用 OperationContext 类的示例,请参阅 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

注解

OperationContext在服务操作中使用 中的 来访问当前操作执行环境。 特别是,操作上下文用于访问双工服务中的回调通道、存储整个操作部分的额外状态数据、访问传入消息头和属性以及添加传出消息头和属性。

有关使用扩展存储状态数据的详细信息,请参阅 可扩展对象

具有以下 OperationContext 属性和方法。

构造函数

OperationContext(IContextChannel)

初始化 OperationContext 类的新实例,该类使用客户端应用程序中指定的 IContextChannel

属性

Channel

获取与当前 OperationContext 对象关联的通道。

ClaimsPrincipal

获取与此操作关联的基于声明的主体。

Current

获取或设置当前线程的执行上下文。

EndpointDispatcher

获取或设置要检查或修改的终结点的终结点调度程序。

Extensions

从当前消息上下文中获取服务扩展集合。

HasSupportingTokens

获取一个值,该值指示传入消息是否具有支持令牌。

Host

获取当前服务对象的 ServiceHost

IncomingMessageHeaders

获取 OperationContext 的传入消息头。

IncomingMessageProperties

获取 OperationContext 中的传入消息的消息属性。

IncomingMessageVersion

获取 OperationContext 的传入 SOAP 消息版本。

InstanceContext

获取管理当前服务实例的 InstanceContext 对象。

IsUserContext

此属性专供系统使用,不应由用户调用。

OutgoingMessageHeaders

获取活动 OperationContext 的传出消息头。

OutgoingMessageProperties

获取活动 OperationContext 中的出站消息的消息属性。

RequestContext

获取或设置此方法的 RequestContext 实现。

ServiceSecurityContext

获取或设置将在其中执行此方法的 ServiceSecurityContext

SessionId

获取用于标识当前会话的 String

SupportingTokens

获取一个 ICollection<T> 类型的 SecurityToken

方法

Equals(Object)

确定指定对象是否等于当前对象。

(继承自 Object)
GetCallbackChannel<T>()

获取调用当前操作的客户端实例的通道。

GetHashCode()

作为默认哈希函数。

(继承自 Object)
GetType()

获取当前实例的 Type

(继承自 Object)
MemberwiseClone()

创建当前 Object 的浅表副本。

(继承自 Object)
SetTransactionComplete()

提交当前正在执行的事务。

ToString()

返回表示当前对象的字符串。

(继承自 Object)

事件

OperationCompleted

操作完成时发生。

适用于