通过上篇文章对WCF做了一个简短的介绍,下面就做一个小例子来熟悉如何构建和应用一个WCF应用。
1.添加WCF服务:
2.打开刚才新建的服务接口IShowMyName,在其中添加方法(注意不要将服务标签丢掉,否则访问不到):
3.添加实现服务的方法:
4.在浏览器中查看如下图所示表示成功:
5.在IIS中对其进行发布,这样服务端就配置好了。
6.客户端的配置,首先要进行配置文件的添加:
(1) 配置好web.config
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_Default"
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/WCFService/ShowMyName.svc?wsdl"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_Default"
contract="Contracts.IShowMyName"
name="BasicHttpBinding_IShowMyName" />
</client>
</system.serviceModel>
</configuration>
(2) 客户端调用服务
在客户端中添加引用:
using System.ServiceModel.Channels;
using System.ServiceModel;
后就可以添加代码,调用WCF的服务了:
//因为服务是通过通道工厂创建的,故在此需要先实例化通道工厂
ChannelFactory<IShowMyName> factory = new ChannelFactory<IShowMyName>
("BasicHttpBinding_IShowMyName");IShowMyName myobject = factory.CreateChannel();
//调用服务的方法
string time = myobject.showName(this.txtName.Text);