ServiceContractAttribute 類別


表示某個介面或類別定義了 Windows Communication Foundation (WCF) 應用程式中的服務合約。Indicates that an interface or a class defines a service contract in a Windows Communication Foundation (WCF) application.

public ref class ServiceContractAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Interface, AllowMultiple=false, Inherited=false)]
public sealed class ServiceContractAttribute : Attribute
public sealed class ServiceContractAttribute : Attribute
[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Interface, Inherited=false)]
public sealed class ServiceContractAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Interface, AllowMultiple=false, Inherited=false)>]
type ServiceContractAttribute = class
    inherit Attribute
type ServiceContractAttribute = class
    inherit Attribute
[<System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Interface, Inherited=false)>]
type ServiceContractAttribute = class
    inherit Attribute
Public NotInheritable Class ServiceContractAttribute
Inherits Attribute


下列程式碼範例會示範如何將 ServiceContractAttribute 套用至介面,定義出含有一個服務方法的服務合約,此服務方法由 OperationContractAttribute 表示。The following code example shows how to apply the ServiceContractAttribute to an interface to define a service contract with one service method, indicated by the OperationContractAttribute. 在此情況下,所有訊息之繫結所要求的保護層級為 ProtectionLevel.EncryptAndSignIn this case, the protection level required of bindings for all messages is ProtectionLevel.EncryptAndSign.

程式碼範例接著在 SampleService 類別上實作該合約。The code example then implements that contract on the SampleService class.

using System;
using System.Collections.Generic;
using System.Net.Security;
using System.ServiceModel;
using System.Text;

namespace Microsoft.WCF.Documentation
  public interface ISampleService{
    string SampleMethod(string msg);

  class SampleService : ISampleService
  #region ISampleService Members

  public string  SampleMethod(string msg)
      return "The service greets you: " + msg;


Imports System.Collections.Generic
Imports System.Net.Security
Imports System.ServiceModel
Imports System.Text

Namespace Microsoft.WCF.Documentation
  <ServiceContract(Namespace:="http://microsoft.wcf.documentation", Name:="SampleService", ProtectionLevel:=ProtectionLevel.EncryptAndSign)> _
  Public Interface ISampleService
    <OperationContract> _
    Function SampleMethod(ByVal msg As String) As String
  End Interface

  Friend Class SampleService
      Implements ISampleService
  #Region "ISampleService Members"

  Public Function SampleMethod(ByVal msg As String) As String Implements ISampleService.SampleMethod
       Return "The service greets you: " & msg
  End Function

  #End Region
  End Class
End Namespace

下列程式碼範例是前述服務的一個簡單組態檔,此服務會建立一個端點。The following code example shows a simple configuration file for the preceding service that creates one endpoint.

            <add baseAddress="http://localhost:8080/SampleService"/>
        <behavior name="mex">
          <serviceMetadata httpGetEnabled="true" httpGetUrl=""/>

下列程式碼範例示範叫用前述 SampleService 的簡單用戶端。The following code example shows a simple client that invokes the preceding SampleService.

using System;
using System.ServiceModel;
using System.ServiceModel.Channels;

public class Client
  public static void Main()
    // Picks up configuration from the config file.
    SampleServiceClient wcfClient = new SampleServiceClient();
        // Making calls.
        Console.WriteLine("Enter the greeting to send: ");
        string greeting = Console.ReadLine();
        Console.WriteLine("The service responded: " + wcfClient.SampleMethod(greeting));

        Console.WriteLine("Press ENTER to exit:");

        // Done with service.
    catch (TimeoutException timeProblem)
      Console.WriteLine("The service operation timed out. " + timeProblem.Message);
    catch(CommunicationException commProblem)
      Console.WriteLine("There was a communication problem. " + commProblem.Message);

Imports System.ServiceModel
Imports System.ServiceModel.Channels

Public Class Client
  Public Shared Sub Main()
    ' Picks up configuration from the config file.
    Dim wcfClient As New SampleServiceClient()
        ' Making calls.
        Console.WriteLine("Enter the greeting to send: ")
            Dim greeting = Console.ReadLine()
        Console.WriteLine("The service responded: " & wcfClient.SampleMethod(greeting))

        Console.WriteLine("Press ENTER to exit:")

        ' Done with service. 
    Catch timeProblem As TimeoutException
      Console.WriteLine("The service operation timed out. " & timeProblem.Message)
    Catch commProblem As CommunicationException
      Console.WriteLine("There was a communication problem. " & commProblem.Message)
    End Try
  End Sub
End Class


使用介面 (或類別) 上的 ServiceContractAttribute 屬性來定義服務合約。Use the ServiceContractAttribute attribute on an interface (or class) to define a service contract. 接著使用一個或多個類別 (或介面) 方法上的 OperationContractAttribute 屬性,定義合約的服務作業。Then use the OperationContractAttribute attribute on one or more of the class (or interface) methods to define the contract's service operations. 當服務合約已 實並與系結和 物件結合時 EndpointAddress ,服務合約就會公開供用戶端使用。When the service contract is implemented and combined with a Bindings and an EndpointAddress object, the service contract is exposed for use by clients. 如需使用簡單範例處理常式的總覽,請參閱 開始使用教學課程。For an overview of the process using simple examples, see Getting Started Tutorial. 如需建立服務合約的詳細資訊,請參閱 設計和執行服務For more information about creating service contracts, see Designing and Implementing Services.

ServiceContractAttribute 表示的資訊及其介面與 Web 服務描述語言 (WSDL) 的 <portType> 項目鬆散相關。The information expressed by a ServiceContractAttribute and its interface is loosely related to the Web Services Description Language (WSDL) <portType> element. 服務端會使用服務合約來指定服務的端點公開給呼叫端的內容。A service contract is used on the service side to specify what the service's endpoint exposes to callers. 用戶端亦會使用服務合約,來指定該用戶端所通訊之端點的合約,而在雙工合約中,也會指定用戶端必須實作的回呼合約 (使用 CallbackContract 屬性),以參與雙工對談。It is also used on the client side to specify the contract of the endpoint with which the client communicates and, in the case of duplex contracts, to specify the callback contract (using the CallbackContract property) that the client must implement in order to participate in a duplex conversation.


ServiceContractAttribute 裝飾的介面或類別至少要有一個以 OperationContractAttribute 屬性標記的方法,才能公開其功能。An interface or class that is decorated with ServiceContractAttribute must also have at least one method marked with the OperationContractAttribute attribute to expose any functionality. 請參閱<範例>一節中,使用這兩個屬性來定義並實作服務的最簡單程式碼範例。See the Examples section for a code example of the simplest use of the two attributes to define and implement a service.

使用 ServiceContractAttribute 屬性修改服務合約。Use the ServiceContractAttribute properties to modify the service contract.

  • ConfigurationName 屬性指定了所使用組態檔中服務項目的名稱。The ConfigurationName property specifies the name of the service element in the configuration file to use.

  • NameNamespace 屬性控制了 WSDL <portType> 元素中的合約名稱與合約命名空間。The Name and Namespace properties control the name and namespace of the contract in the WSDL <portType> element.

  • SessionMode 屬性指定合約是否需要支援工作階段的繫結。The SessionMode property specifies whether the contract requires a binding that supports sessions.

  • CallbackContract 屬性指定雙向 (雙工) 對談的傳回合約。The CallbackContract property specifies the return contract in a two-way (duplex) conversation.

  • HasProtectionLevelProtectionLevel 屬性表示支援合約的所有訊息是否有明確的 ProtectionLevel 值,若有,其值為何。The HasProtectionLevel and ProtectionLevel properties indicate whether all messages supporting the contract have a explicit ProtectionLevel value, and if so, what that level is.

服務會實作服務合約,代表服務類型支援的資料交換。Services implement service contracts, which represent the data exchange that a service type supports. 服務類別可實作服務合約 (藉由實作以 ServiceContractAttribute 標記的介面,此介面有以 OperationContractAttribute 標記的方法),或可用 ServiceContractAttribute 標記此類別,並套用 OperationContractAttribute 屬性至此類別的方法 A service class can implement a service contract (by implementing an interface marked with ServiceContractAttribute that has methods marked with OperationContractAttribute) or it can be marked with the ServiceContractAttribute and apply the OperationContractAttribute attribute to its own methods. (如果類別會執行以標記的介面 ServiceContractAttribute ,它本身不能標示為 ServiceContractAttribute 。在以標記的服務類型上 ) 方法 OperationContractAttribute 會視為服務類型本身所指定之預設服務合約的一部分。(If a class implements an interface marked with ServiceContractAttribute, it cannot be itself marked with ServiceContractAttribute.) Methods on service types that are marked with the OperationContractAttribute are treated as part of a default service contract specified by the service type itself. 如需服務作業的詳細資訊,請參閱 OperationContractAttributeFor details about service operations, see OperationContractAttribute.

根據預設,NameNamespace 屬性分別為合約類型名稱與 的名稱,而 ProtectionLevel 則為 ProtectionLevel.NoneBy default, the Name and Namespace properties are the name of the contract type and, respectively, and ProtectionLevel is ProtectionLevel.None. 建議您使用這些屬性,明確設定服務合約的名稱、命名空間與保護層級。It is recommended that service contracts explicitly set their names, namespaces, and protection levels using these properties. 如此可達成兩個目標,Doing so accomplishes two goals. 首先,它會建置一份不會與 Managed 型別資訊直接連接的合約,可讓您在不破壞 WSDL 所表示的合約下,重構 Managed 程式碼與命名空間。First, it builds a contract that is not directly connected to the managed type information, enabling you to refactor your managed code and namespaces without breaking the contract as it is expressed in WSDL. 還有,在合約內明確要求某種保護層級,可讓執行階段驗證該繫結組態是否支援該安全性層級,避免因組態設定不當而洩漏敏感資訊。Second, explicitly requiring a certain level of protection on the contract itself enables the runtime to validate whether the binding configuration supports that level of security, preventing poor configuration from exposing sensitive information. 如需保護層級的詳細資訊,請參閱 瞭解保護層級For more information about protection levels, see Understanding Protection Level.

若要公開服務供用戶端應用程式使用,請建立主機應用程式,以 Windows Communication Foundation (WCF) 註冊您的服務端點。To expose a service for use by client applications, create a host application to register your service endpoint with Windows Communication Foundation (WCF). 您可以使用 Windows 啟用服務來裝載 WCF 服務, () 、主控台應用程式、Windows 服務應用程式、ASP.NET 應用程式、Windows Forms 應用程式或任何其他類型的應用程式域。You can host WCF services using Windows Activation Services (WAS), in console applications, Windows Service applications, ASP.NET applications, Windows Forms applications, or any other kind of application domain.

在 WAS 裝載的方式與建立 ASP.NET 應用程式非常相似。Hosting in the WAS is very similar to creating an ASP.NET application. 如需詳細資訊,請參閱 如何:在 IIS 中裝載 WCF 服務For details, see How to: Host a WCF Service in IIS.

用戶端使用服務合約介面 (以 ServiceContractAttribute 標示的介面) 建立通往服務的通道,或使用用戶端物件 (結合了服務合約介面的型別資訊與 ClientBase<TChannel> 類別) 與您的服務通訊。Clients either use the service contract interface (the interface marked with ServiceContractAttribute) to create a channel to the service or they use the client objects (which combine the type information of the service contract interface with the ClientBase<TChannel> class) to communicate with your service. 如需服務用戶端通道的詳細資訊,請參閱 ChannelFactory<TChannel> 類別和 WCF 用戶端總覽For details on client channels to services, see the ChannelFactory<TChannel> class and WCF Client Overview.

使用 ServiceContractAttribute 類別或介面來繼承另一個延伸了父合約的 ServiceContractAttribute 類別或介面。Using a ServiceContractAttribute class or interface to inherit from another ServiceContractAttribute class or interface extends the parent contract. 例如,如果 IChildContract 介面以 ServiceContractAttribute 標記,並繼承了另一個服務合約介面 IParentContract,則 IChildContract 服務合約就包含了 IParentContractIChildContract 的方法。For example, if an IChildContract interface is marked with ServiceContractAttribute and inherited from another service contract interface, IParentContract, the IChildContract service contract contains the methods of both IParentContract and IChildContract. 延伸合約 (在類別或介面上) 與延伸 Managed 類別與介面非常相似。Extending contracts (whether on classes or interfaces) is very similar to extending managed classes and interfaces.

建立服務最有彈性的方式,是先定義服務合約介面,再讓您的服務類別實作該介面 The most flexible approach to creating services is to define service contract interfaces first and then have your service class implement that interface. (如果您必須執行由其他人定義的服務合約,這也是建立服務的最簡單方式。 ServiceContractAttribute OperationContractAttribute 當服務只公開一個合約 (但該合約可由一個以上的端點) 公開時,) 使用來標記具有和其方法的類別,即可直接建立服務。(This is also the simplest way to build your services if you must implement service contracts that have been defined by others.) Building services directly by marking a class with ServiceContractAttribute and its methods with OperationContractAttribute works when the service exposes only one contract (but that contract can be exposed by more than one endpoint).

您可以使用 CallbackContract 屬性來表示另一個服務合約,當與原始服務合約系結時,會定義可個別以兩種方式流動的訊息交換。Use the CallbackContract property to indicate another service contract that, when bound together with the original service contract, define a message exchange that can flow in two ways independently. 如需詳細資訊,請參閱 CallbackContractFor details, see CallbackContract.



初始化 ServiceContractAttribute 類別的新執行個體。Initializes a new instance of the ServiceContractAttribute class.



當合約是雙工合約時,取得或設定回呼合約的型別。Gets or sets the type of callback contract when the contract is a duplex contract.


取得或設定用來在應用程式組態檔中尋找服務的名稱。Gets or sets the name used to locate the service in an application configuration file.


取得指出成員是否已指派保護層級的值。Gets a value that indicates whether the member has a protection level assigned.


取得或設定 Web 服務描述語言 (WSDL) 中的 <portType> 項目名稱。Gets or sets the name for the <portType> element in Web Services Description Language (WSDL).


取得或設定 Web 服務描述語言 (WSDL) 中 <portType> 項目的命名空間。Gets or sets the namespace of the <portType> element in Web Services Description Language (WSDL).


指定合約繫結是否必須支援 ProtectionLevel 屬性的值。Specifies whether the binding for the contract must support the value of the ProtectionLevel property.


取得或設定是否允許工作階段、不允許工作階段,或需要工作階段。Gets or sets whether sessions are allowed, not allowed or required.


在衍生類別中實作時,取得這個 Attribute 的唯一識別碼。When implemented in a derived class, gets a unique identifier for this Attribute.

(繼承來源 Attribute)



傳回值,這個值指出此執行個體是否與指定的物件相等。Returns a value that indicates whether this instance is equal to a specified object.

(繼承來源 Attribute)

傳回這個執行個體的雜湊碼。Returns the hash code for this instance.

(繼承來源 Attribute)

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

(繼承來源 Object)

在衍生類別中覆寫時,表示這個執行個體的值是衍生類別的預設值。When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class.

(繼承來源 Attribute)

在衍生類別中覆寫時,會傳回值,表示這個執行個體是否等於指定物件。When overridden in a derived class, returns a value that indicates whether this instance equals a specified object.

(繼承來源 Attribute)

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

(繼承來源 Object)

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

(繼承來源 Object)


_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

將一組名稱對應至一組對應的分派識別項 (Dispatch Identifier)。Maps a set of names to a corresponding set of dispatch identifiers.

(繼承來源 Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

擷取物件的類型資訊,可以用來取得介面的類型資訊。Retrieves the type information for an object, which can be used to get the type information for an interface.

(繼承來源 Attribute)

擷取物件提供的類型資訊介面數目 (0 或 1)。Retrieves the number of type information interfaces that an object provides (either 0 or 1).

(繼承來源 Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

提供物件所公開的屬性和方法的存取權。Provides access to properties and methods exposed by an object.

(繼承來源 Attribute)