1.首先先建立一個WCF服務應用程序
2.再建立一個宿主程序,這里用控制台,添加服務引用,這里會報錯:
點擊頁面確定,回到添加服務頁面
點擊箭頭有如下內容:
這里告訴我們問題的所在,我們只要重新生成解決方案就行了。
好,重新生成解決方案,ok,問題解決,添加引用服務成功。
3.在控制台程序里啟動服務:
static void Main(string[] args) { using (ServiceHost host = new ServiceHost(typeof(WcfService2.Service1))) { host.Opened += (a, b) => { Console.WriteLine("service is opened"); }; host.Open(); Console.Read();
} }
這里先把控制台程序設為啟動項目
4.運行程序,報錯:“服務“WcfService1.Service1”有零個應用程序(非基礎結構)終結點。這可能是因為未找到應用程序的配置文件,或者在配置文件中未找到與服務名稱匹配的服務元素,或者服務元素中未定義終結點”。
這個問題是宿主的配置文件出現問題,如果宿主是控制台,請修改app.config 配置:代碼如下
<?xml version="1.0" encoding="utf-8" ?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> <system.serviceModel> <services> <service name="WcfService2.Service1" behaviorConfiguration="MessageBehavior" > <host> <baseAddresses > <add baseAddress="http://localhost:13563/WcfService2"/> </baseAddresses> </host> <endpoint address="" binding="wsHttpBinding" contract="WcfService2.IService1"></endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint> </service> </services> <behaviors> <serviceBehaviors> <behavior name="MessageBehavior"> <!-- 為避免泄漏元數據信息,請在部署前將以下值設置為 false --> <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/> <!-- 要接收故障異常詳細信息以進行調試,請將以下值設置為 true。在部署前設置為 false 以避免泄漏異常信息 --> <serviceDebug includeExceptionDetailInFaults="true"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> </configuration>
5.好問題解決,但是又出現新的問題:HTTP 無法注冊 URL http://+:13563/WcfService2/。進程不具有此命名空間的訪問權限(有關詳細信息,請參見 http://go.microsoft.com/fwlink/?LinkId=70353)。
這個問題主要是win7或者win8系統權限問題,點擊vs啟動程序,右鍵點“以管理員身份”運行程序即可解決
6.關閉VS2010,以管理員身份運行
好,終於成功了
7.調用
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ServiceModel; namespace WcfService1 { class Program { static void Main(string[] args) { ConsoleApplication1.ServiceReference1.Service1Client wcfClient = new ConsoleApplication1.ServiceReference1.Service1Client(); System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); watch.Start(); Console.WriteLine( wcfClient.GetData(10)); watch.Stop(); Console.WriteLine("耗時:" + watch.ElapsedMilliseconds); Console.ReadKey(); } } }
結果:
終於成功了,我因為是初學,所有才會出現這么多問題,希望能幫到和我一樣的初學者,如果那個高手有簡便后者快捷的方法,可以告訴我,我這方法太笨了。期待你的指點。