作法:使用合約介面來建立服務

Windows Communication Foundation (WCF) 合約的慣用方式是使用介面。 此合約可指定存取服務提供之作業時所需的訊息集合與結構。 此介面可將 ServiceContractAttribute 類別套用到介面,並將 OperationContractAttribute 類別套用到您想要公開的方法上,藉此定義輸入與輸出類型。

如需服務合約的詳細資訊,請參閱設計服務合約 (機器翻譯)

使用介面來建立 WCF 合約

  1. 使用 Visual Basic、C# 或其他任何的通用語言執行平台語言,建立新的介面。

  2. ServiceContractAttribute 類別套用到介面。

  3. 在介面中定義方法。

  4. OperationContractAttribute 類別套用到每個方法 (必須當成公開 WCF 合約的一部分加以公開) 上。

範例

下列程式碼範例會顯示可定義服務合約的介面。

using System.ServiceModel;

[ServiceContract]
public interface ICalculator
{
   [OperationContract]
   double Add(double n1, double n2);
   [OperationContract]
   double Subtract(double n1, double n2);
   [OperationContract]
   double Multiply(double n1, double n2);
   [OperationContract]
   double Divide(double n1, double n2);
}


<ServiceContract()> _
Public Interface ICalculator
    <OperationContract()> _
    Function Add(ByVal n1 As Double, ByVal n2 As Double) As Double
    <OperationContract()> _
    Function Subtract(ByVal n1 As Double, ByVal n2 As Double) As Double
    <OperationContract()> _
    Function Multiply(ByVal n1 As Double, ByVal n2 As Double) As Double
    <OperationContract()> _
    Function Divide(ByVal n1 As Double, ByVal n2 As Double) As Double
End Interface

已套用 OperationContractAttribute 類別的方法依預設會使用要求-回覆訊息模式。 如需此訊息模式的詳細資訊,請參閱如何:建立要求-回覆合約 (機器翻譯)。 您也可以設定屬性 (Attribute) 的屬性 (Property) 來建立並使用其他訊息模式。 如需更多範例,請參閱如何:建立單面合約 (機器翻譯),以及如何:建立雙面合約 (機器翻譯)

另請參閱