客户端和元数据WCF Client and Metadata
WCF客户端
WCF客户端应用程序的创建,是为了将服务端的操作转换成方法,任何一种应用程序都可以托管WCF客户端,包括那些托管了服务端的应用程序。因此,可以创建一个WCF服务端,同时包含另外一个服务的客户端。
客户端应用程序是一个可配置的应用程序,它使用WCF客户端技术与另外一个应用程序进行通信,创建一个可以使用WCF服务的客户端应用程序需要以下的步骤。
1.取得代理类,服务,终结点信息
使用SvcUtil.exe我们可以创建服务的代理类以及终结点信息的配置。例如,在Visual Studio命令行工具中输入下面的命令,就会自动生成class文件,并且为这个类文件添加上终结点的相关信息。
svcutil /language:vb /out:ClientCode.vb /config:app.config http://localhost:8090/MyService/SimpleCalculator.svc?wsdl
2.调用方法
将这个类文件添加到客户端应用程序中,然后创建类对象,并且调用服务方法。我们通过上一步取得配置信息需要被添加到客户端应用程序的配置文件中,当调用第一步方法的时候,WCF会自动的打开默认的信道,当对象被回收的时候,信道也会被关闭。
//Creating the proxy on client side MyCalculatorServiceProxy.MyServiceProxy proxy = new MyCalculatorServiceProxy.MyServiceProxy(); Console.WriteLine("Counter: " + proxy.MyMethod());
3.关闭WCF客户端对象
当使用完上面创建的对象之后,我们需要去释放对象,当对象被清理的时候,信道也会随着服务一起被关闭。
元数据
元数据的作用是用来描述服务的特征的。这些元数据公布给客户端程序,用来指导客户端程序如何与服务端进行通信。元数据的配置在服务端配置文件的<ServcieBehaviour>下面的<ServiceMetadata>属性中
<system.serviceModel> <services> <service name="MathService" behaviorConfiguration="MathServiceBehavior"> <endpoint address="" contract="IMathService" binding="wsHttpBinding"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="MathServiceBehavior"> <serviceMetadata httpGetEnabled="True"/> <serviceDebug includeExceptionDetailInFaults="true" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel>