| 一個WCF的HelloWorld程序要解決的問題: WCF入門,創(chuàng)建一個HelloWorld程序。 解決方法: 
 
 在項目上右鍵,Add Reference->選擇.NET標簽頁,再找到System.ServiceModel 添加。 效果如下圖所示,并將Host項目設(shè)為啟動項目。 
 2.在Contracts項目中定義服務(wù)契約接口。  IHello namespace Contracts { [ServiceContract] public interface IHello { [OperationContract] void Hello(); } } 
 3.在Services項目中實現(xiàn)Contracts項目中的接口。  HelloWorld實現(xiàn)IHello namespace Services { public class HelloWorld : IHello { public void Hello() { Console.WriteLine(" Hello world"); } } 
 4.在Host項目為WCF的服務(wù)提供運行環(huán)境。  HostApp using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; using Services; using Contracts; using System.ServiceModel.Description; namespace Host { /// <summary> /// This is a Host Console application /// </summary> public class HostApp { static void Main(string[] args) { /** * Create a host to provide service. * ServiceType is HelloWorld * BaseAddress is in localhost */ ServiceHost host = new ServiceHost(typeof(HelloWorld), new Uri("http://localhost:8080/HelloService")); /** * Add an serviceEndpoint to this host * Implemented Contract is IHello * Binding pattern is BasicHttpBinding * Address 'SVC' is a relative address */ host.AddServiceEndpoint(typeof(IHello), new BasicHttpBinding(),"SVC"); if (host.Description.Behaviors.Find<ServiceMetadataBehavior>() == null) { ServiceMetadataBehavior behavior = new ServiceMetadataBehavior(); behavior.HttpGetEnabled = true; behavior.HttpGetUrl = new Uri("http://localhost:8080/HelloService"); host.Description.Behaviors.Add(behavior); } /** * Once you add an endpoint to ServiceHost,it can create a EndpointListener for each ServiceEndpoint * ServiceDescription is involved in the creating process */ host.Open(); Console.WriteLine("Start Your Service."); Console.ReadKey(); host.Close(); } } } 
 5.啟動Host中的服務(wù),也就是運行Host項目。出現(xiàn)下圖效果,暫時先別關(guān)閉這個窗口。 
 
 6.在你的瀏覽器地址欄中,輸入http://localhost:8080/HelloService出現(xiàn)效果如下: 
 
 7.點擊頁面中的鏈接,出現(xiàn)WSDL格式的XML文件: 
 
 8.經(jīng)過上面這一系列,說明你的服務(wù)端已經(jīng)OK了,現(xiàn)在進行客戶端的配置。 另開一個solution,新建一個名為Client的控制臺程序(什么應(yīng)用程序都行)。添加對System.ServiceModel的引用。 接著,在Client項目上右鍵,Add Service Reference. 接著如下圖:(你前面的Host項目請保持運行狀態(tài)) 
 
 9,在Client端添加調(diào)用的Host服務(wù)的代碼。代碼里面IHello接口命名空間你可以在Client項目的Service Reference中找到,也就是你前一步輸入的Namespace。  Client調(diào)用Hello服務(wù) namespace Client { public class ClientApp { static void Main(String[] args) { ServiceEndpoint httpEndpoint = new ServiceEndpoint(ContractDescription.GetContract(typeof(IHello)), new BasicHttpBinding(), new EndpointAddress("http://localhost:8080/HelloService/SVC")); using (ChannelFactory<IHello> factory = new ChannelFactory<IHello>(httpEndpoint)) { IHello service = factory.CreateChannel(); service.Hello(); } } } } 
 10. OK,現(xiàn)在你再運行你的Client項目??刂婆_下面會多出一行HelloWorld,至此一個最簡單的WCF程序完成了。 
 
 工作原理: 這個程序中的配置,都是用代碼寫的,實際中應(yīng)該在config文件里寫。雖然效果是一樣的,但代碼需要再編譯,所以XML好點。 具體我還是下一篇再寫吧,不然太多了。 
 
 分類: WCF入門筆記 標簽: WCF | 
|  | 
來自: 昵稱10504424 > 《Wcf》