在目前的二次開發項目中,一些信息是放在客戶那里的,只給你一個服務地址,不知道具體有什么方法,每次想調用一個服務不知道能不能實現目前的需求,只能測試。寫個測試程序真的划不來,占用時間不說,而且你忙了一上午,發現那個服務,並不是你想要的。只能說白忙了......下面簡單介紹一下,從同事那里學到的怎么使用VS自帶的測試客戶端。操作很簡單,但很實用。知道這個的,就不用說了,這篇文章就是幫助那些不知道的小伙伴的......
一個簡單的WCF服務端:
契約:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.ServiceModel; 7 namespace Wolfy.Contract 8 { 9 [ServiceContract(Namespace="http://www.wolfy.com")] 10 public interface ICalculator 11 { 12 [OperationContract] 13 double Add(double x,double y); 14 } 15 }
服務:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using Wolfy.Contract; 7 namespace Wolfy.Service 8 { 9 public class CalculatorService : ICalculator 10 { 11 #region ICalculator 成員 12 13 public double Add(double x, double y) 14 { 15 return x + y; 16 } 17 18 #endregion 19 } 20 }
這里就用控制台來承載服務了
控制台代碼開啟服務:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using Wolfy.Contract; 7 using Wolfy.Service; 8 using System.ServiceModel; 9 namespace Wolfy.Server 10 { 11 class Program 12 { 13 static void Main(string[] args) 14 { 15 16 using (ServiceHost host = new ServiceHost(typeof(CalculatorService))) 17 { 18 19 host.Opened += delegate 20 { 21 Console.WriteLine("calculatorService已啟動,按任意鍵停止服務"); 22 }; 23 host.Open(); 24 Console.Read(); 25 } 26 } 27 } 28 }
服務端配置文件:
1 <?xml version="1.0"?> 2 <configuration> 3 <startup> 4 <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/> 5 </startup> 6 <system.serviceModel> 7 <behaviors> 8 <serviceBehaviors> 9 <behavior name="MyServiceBehavior"> 10 <serviceMetadata httpGetEnabled="true"/> 11 </behavior> 12 </serviceBehaviors> 13 </behaviors> 14 <services> 15 <service name="Wolfy.Service.CalculatorService" behaviorConfiguration="MyServiceBehavior"> 16 <endpoint contract="Wolfy.Contract.ICalculator" binding="wsHttpBinding"></endpoint> 17 <host> 18 <baseAddresses> 19 <add baseAddress="http://127.0.0.1:8888/calculatorservice"/> 20 </baseAddresses> 21 </host> 22 </service> 23 </services> 24 </system.serviceModel> 25 </configuration>
一個簡單的WCFdemo算完成了,現在開啟服務....
打開VS測試客戶端
在開發人員命令提示中輸入:wcftestclient回車
然后右鍵我的項目:輸入你的服務地址,當然這里你的服務要在開啟的狀態。
為參數賦值:
結果:
很簡單吧,雖然不是很高深的東西,但很實用,如果您覺得對你有所幫助,那就【推薦】一下吧,畢竟大家知道才是真的知道。