入門示例

該服務描述了它在服務合同中執行的操作,它作為後設資料公開公開。

// Define a service contract.  
[ServiceContract(Namespace="http://StackOverflow.ServiceModel.Samples")]  
public interface ICalculator  
{  
    [OperationContract]  
    double Add(double n1, double n2);
}

服務實現計算並返回適當的結果,如以下示例程式碼所示。

// Service class that implements the service contract.  
public class CalculatorService : ICalculator  
{  
    public double Add(double n1, double n2)  
    {  
        return n1 + n2;  
    }
}

該服務公開了一個端點,用於與使用配置檔案(Web.config)定義的服務進行通訊,如以下示例配置所示。

<services>  
    <service   
        name="StackOverflow.ServiceModel.Samples.CalculatorService"  
        behaviorConfiguration="CalculatorServiceBehavior">  
        <!-- ICalculator is exposed at the base address provided by  
         host: http://localhost/servicemodelsamples/service.svc.  -->  
       <endpoint address=""  
              binding="wsHttpBinding"  
              contract="StackOverflow.ServiceModel.Samples.ICalculator" />  
       ...  
    </service>  
</services>

預設情況下,框架不會公開後設資料。因此,該服務開啟 ServiceMetadataBehavior 並在 http://localhost/servicemodelsamples/service.svc/mex 中公開後設資料交換(MEX)端點。以下配置演示了這一點。

<system.serviceModel>  
  <services>  
    <service   
        name="StackOverflow.ServiceModel.Samples.CalculatorService"  
        behaviorConfiguration="CalculatorServiceBehavior">  
      ...  
      <!-- the mex endpoint is explosed at  
       http://localhost/servicemodelsamples/service.svc/mex -->  
      <endpoint address="mex"  
                binding="mexHttpBinding"  
                contract="IMetadataExchange" />  
    </service>  
  </services>  

  <!--For debugging purposes set the includeExceptionDetailInFaults  
   attribute to true-->  
  <behaviors>  
    <serviceBehaviors>  
      <behavior name="CalculatorServiceBehavior">  
        <serviceMetadata httpGetEnabled="True"/>  
        <serviceDebug includeExceptionDetailInFaults="False" />  
      </behavior>  
    </serviceBehaviors>  
  </behaviors>  
</system.serviceModel>  

客戶端使用由 ServiceModel 後設資料實用工具(Svcutil.exe)生成的客戶端類使用給定的合同型別進行通訊。

從客戶端目錄中的 SDK 命令提示符執行以下命令以生成型別化代理:

svcutil.exe /n:"http://StackOverflow.ServiceModel.Samples,StackOverflow.ServiceModel.Samples" http://localhost/servicemodelsamples/service.svc/mex /out:generatedClient.cs  

與服務一樣,客戶端使用配置檔案(App.config)來指定要與之通訊的端點。客戶端端點配置包含服務端點的絕對地址,繫結和合同,如以下示例所示。

<client>  
     <endpoint  
         address="http://localhost/servicemodelsamples/service.svc"   
         binding="wsHttpBinding"   
         contract="StackOverflow.ServiceModel.Samples.ICalculator" />  
</client>  

客戶端實現例項化客戶端並使用型別化介面開始與服務通訊,如以下示例程式碼所示。

// Create a client.  
CalculatorClient client = new CalculatorClient();  

// Call the Add service operation.  
double value1 = 100.00D;  
double value2 = 15.99D;  
double result = client.Add(value1, value2);  
Console.WriteLine("Add({0},{1}) = {2}", value1, value2, result); 

//Closing the client releases all communication resources.  
client.Close();