创建一个 WCF Client 也可以通过2种方式,直接使用代码 或 使用工具来创建。
(源代码实例下载)
方式 一:直接使用代码
第一步:创建一个简单的 Windows Console 工程。加入一个和WCF Service端一致的接口文件。其中也需要引入 System.Model和使用关键字 [ServiceContract]来描述接口。
using System;
using System.ServiceModel;
[ServiceContract]
public interface IAddTax
{
[OperationContract]
decimal AddTax(decimal productCost, double taxRate);
}
第二步:创建ChannelFactory Class,用以创建Channel和Service端进行通信。
EndpointAddress address = new EndpointAddress("http://localhost:8080/AddTaxService");
BasicHttpBinding binding = new BasicHttpBinding();
ChannelFactory<IAddTax> myChannelFactory = new ChannelFactory<IAddTax>(binding, address);
IAddTax wcfClient = myChannelFactory.CreateChannel();
第三步:创建一些测试性的代码用以和WCF Service 进行通信和测试。
decimal price = default(decimal);
decimal total = default(decimal);
double rate = default(double);
Console.Write("Enter the product cost: $");
price = Convert.ToDecimal(Console.ReadLine());
Console.Write("Enter the tax rate(double): %");
rate = Convert.ToDouble(Console.ReadLine());
total = wcfClient.AddTax(price, rate);
Console.WriteLine("Total price=", total);
Console.ReadLine();
myChannelFactory.Close();
使用代码创建一个WCF Client相对简单。
实例代码下载:使用代码实现的 WCF Client Application。
方式 二:使用工具创建WCF Client
通过使用工具主要是创建 Proxy 和 Configuration File。
工具:VS2010下的 Add Service Reference 简称 ASR 工具。
ASR 工具的主要作用是获取 WCF Service 端的metadata来生成 WCF Client端的Proxy和Configuration File(其中存储了 address,binding,和contract)。
ASR 使用svcutil.exe来创建Proxy。这个程序可以和 Metadata Exchange来进行通信,来获取 Service端的接口定义信息。Client端根据这些信息可以知道怎样和Service端进行通信了。
第一步:添加一个ASR。
注意:此时一定要启动 目的 WCF Service。
第二步:通过WCF Service的地址我们可以找到WCF Service
第三步:系统自动创建了 WCF Client 的配置文件 app.config。
下面的文件是由系统自动创建的,其中包括了和 WCF Service端通信的基本信息。
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IAddTax" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:8080/AddTaxService" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IAddTax" contract="ServiceReference1.IAddTax"
name="BasicHttpBinding_IAddTax" />
</client>
</system.serviceModel>
</configuration>
第四步:
除了使用VS2010图形工具外,我们还可以直接使用 svcutil.exe命令行来创建。
ASR tool 还支持为ASMX Service创建Client,使用方式与上述方法一致