OperationContext 類別

定義

提供服務方法執行內容的存取。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)
繼承
OperationContext
實作

範例

下列程式碼範例會使用 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 Forms 用戶端)可以從服務接收任意數目的呼叫。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

下列用戶端會執行, 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 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 類別的新執行個體。Initializes a new instance of the OperationContext class that uses the specified IContextChannel in a client application.

屬性

Channel

取得與目前 OperationContext 物件相關聯的通道。Gets the channel associated with the current OperationContext object.

ClaimsPrincipal

取得與作業相關聯的宣告架構主體。Gets the claims-based principal associated with the operation.

Current

取得或設定目前執行緒的執行內容。Gets or sets the execution context for the current thread.

EndpointDispatcher

取得或設定要檢查或修改的端點之端點發送器。Gets or sets the endpoint dispatcher for the endpoint to inspect or modify.

Extensions

從目前訊息內容取得服務擴充部分的集合。Gets the collection of service extensions from the current message context.

HasSupportingTokens

取得值,這個值表示傳入訊息是否支援權杖。Gets a value that indicates whether the incoming message has supporting tokens.

Host

取得目前服務物件的 ServiceHostGets the ServiceHost for the current service object.

IncomingMessageHeaders

取得 OperationContext 的傳入訊息標頭。Gets the incoming message headers for the OperationContext.

IncomingMessageProperties

取得 OperationContext 中傳入訊息的訊息屬性。Gets the message properties for the incoming message in the OperationContext.

IncomingMessageVersion

取得 OperationContext 的傳入 SOAP 訊息版本。Gets the incoming SOAP message version for the OperationContext.

InstanceContext

取得管理目前服務執行個體的 InstanceContext 物件。Gets the InstanceContext object that manages the current service instance.

IsUserContext

本屬性僅供系統使用,使用者不應呼叫。This property is intended for system use and should not be called by users.

OutgoingMessageHeaders

取得使用中 OperationContext 的傳出訊息標頭。Gets the outgoing message headers for the active OperationContext.

OutgoingMessageProperties

取得使用中 OperationContext 內的傳出訊息之訊息屬性。Gets the message properties for the outbound message in the active OperationContext.

RequestContext

取得或設定本方法的 RequestContext 實作。Gets or sets the RequestContext implementation for this method.

ServiceSecurityContext

取得或設定 ServiceSecurityContext,此方法會在其中執行。Gets or sets the ServiceSecurityContext within which this method executes.

SessionId

取得用來識別目前工作階段的 StringGets the String used to identify the current session.

SupportingTokens

取得 ICollection<T> 型別的 SecurityTokenGets a ICollection<T> of type SecurityToken.

方法

Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(繼承來源 Object)
GetCallbackChannel<T>()

取得至用戶端執行個體的通道,此通道呼叫了目前作業。Gets a channel to the client instance that called the current operation.

GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(繼承來源 Object)
GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(繼承來源 Object)
MemberwiseClone()

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

(繼承來源 Object)
SetTransactionComplete()

認可目前執行的異動。Commits the currently executing transaction.

ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(繼承來源 Object)

事件

OperationCompleted

發生於作業已經完成時。Occurs when the operation has completed.

適用於