1) 打開Visual Studio 2012,在菜單上點擊文件—>新建—>項目—>WCF服務應用程序。在彈出界面的“名稱”對應的文本框中輸入“WcfServiceTest”,然后點擊“確定”按鈕。
如下圖:
2) 把Visual Studio 2012自動生成的兩個文件IService1.cs改名為IService.cs接口類、Service1.cs改名為Service.cs實現類。
如下圖:
3) 由於Visual Studio 2012默認生成的app.config中的配置信息是以IService來寫的配置。
如下:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<compilation targetFramework="4.0" />
</system.web>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<behaviors>
<endpointBehaviors>
<behavior name="RestBehavior">
<webHttp helpEnabled="true" defaultBodyStyle="Bare" defaultOutgoingResponseFormat="Json" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IService" />
</basicHttpBinding>
<webHttpBinding>
<binding name="webHttpBindingConfig" sendTimeout="00:00:40" bypassProxyOnLocal="false" maxReceivedMessageSize="652428800">
<readerQuotas maxStringContentLength="65242880" maxArrayLength="65242880" />
</binding>
</webHttpBinding>
</bindings>
<services>
<service name="WcfService.IService">
<endpoint address="" behaviorConfiguration="RestBehavior" binding="webHttpBinding" bindingConfiguration="webHttpBindingConfig" contract="WcfService.IService">
<identity>
<dns value="Localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<standardEndpoints/>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<!-- 若要在調試過程中瀏覽 Web 應用程序根目錄,請將下面的值設置為 True。 在部署之前將該值設置為 False 可避免泄露 Web 應用程序文件夾信息。 -->
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
4) 右鍵WcfServiceTest項目選址[發布]。
如下圖:
5) 控制面板 - 管理工具 - Internet 信息服務(IIS)管理器 - 選址[網站]節點 添加網站。
如下圖:
6) 新建一個測試項目添加服務引用。
如下圖:
7) 服務接口調用如下。
//1.ServiceClient sc = new ServiceClient(); //2.ServiceClient sc = new ServiceClient("BasicHttpBinding_IService", "http://192.168.99.64:9999/WcfService.Service.svc");
ServiceClient sc = new ServiceClient(); string strRst = sc.GetData(100);