要解決的問題:
WCF入門,創建一個HelloWorld程序。
解決方法:
- 打開VS,創建一個空白的solution。然后依次創建下面三個項目:
- Contracts:類庫項目,添加System.ServiceModel的引用。
- Services:類庫項目,添加System.ServiceModel和對Contracts項目的引用。
- Host:控制台項目,田間System.ServiceModel和對Contracts、Services項目的引用。
在項目上右鍵,Add Reference->選擇.NET標簽頁,再找到System.ServiceModel 添加。
效果如下圖所示,並將Host項目設為啟動項目。
2.在Contracts項目中定義服務契約接口。

namespace Contracts { [ServiceContract] public interface IHello { [OperationContract] void Hello(); } }
3.在Services項目中實現Contracts項目中的接口。

namespace Services { public class HelloWorld : IHello { public void Hello() { Console.WriteLine(" Hello world"); } }
4.在Host項目為WCF的服務提供運行環境。

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中的服務,也就是運行Host項目。出現下圖效果,暫時先別關閉這個窗口。
6.在你的瀏覽器地址欄中,輸入http://localhost:8080/HelloService出現效果如下:
7.點擊頁面中的鏈接,出現WSDL格式的XML文件:
8.經過上面這一系列,說明你的服務端已經OK了,現在進行客戶端的配置。
另開一個solution,新建一個名為Client的控制台程序(什么應用程序都行)。添加對System.ServiceModel的引用。
接着,在Client項目上右鍵,Add Service Reference. 接着如下圖:(你前面的Host項目請保持運行狀態)
9,在Client端添加調用的Host服務的代碼。代碼里面IHello接口命名空間你可以在Client項目的Service Reference中找到,也就是你前一步輸入的Namespace。

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,現在你再運行你的Client項目。控制台下面會多出一行HelloWorld,至此一個最簡單的WCF程序完成了。
工作原理:
這個程序中的配置,都是用代碼寫的,實際中應該在config文件里寫。雖然效果是一樣的,但代碼需要再編譯,所以XML好點。
具體我還是下一篇再寫吧,不然太多了。