入门示例

该服务描述了它在服务合同中执行的操作,它作为元数据公开公开。

// 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();