一、WCF是什么?
Windows Communication Foundation(WCF)是由微軟開發的一系列支持數據通信的應用程序框架,整合了原有的windows通訊的 .net Remoting,WebService,Socket的機制,並融合有Http和Ftp的相關技術,是Windows平台上開發分布式應用最佳的實踐方式。使用該框架,開發人員可以構建跨平台、安全、可靠和支持事務處理的企業級互聯應用解決方案。
二、WCF的優勢
1.統一性
WCF涵蓋了之前微軟推出的所有用於分布式開發的技術,包括Remoting、Web Services、WSE、MSMQ等,並以一種統一的編程模式來實現。
2.互操作性
WCF最基本的通信機制是SOAP(Simple Object Access Protocol 簡易對象訪問協議),這就保證了系統之間的互操作性,也能夠實現.NET客戶端與.NET服務端的通信,提供了分布式事務的支持。
3.安全性和可靠性
WCF在安全性上,它完全遵循了WS-*的標准,在SOAP 的header中增加了WS-ReliableMessaging允許可信賴的端對端通信。而建立在WS-Coordination和WS- AtomicTransaction之上的基於SOAP格式交換的信息,則支持兩階段的事務提交(two-phase commit transactions)。
4.兼容性
WCF充分的考慮到了與舊有系統的兼容性。安裝WCF並不會影響原有的技術如ASMX和.Net Remoting。即使對於WCF和ASMX而言,雖然兩者都使用了SOAP,但基於WCF開發的應用程序,仍然可以直接與ASMX進行交互。
特性 |
Web Service |
.NET Remoting |
Enterprise Services |
WSE |
MSMQ |
WCF |
具有互操作性的Web服務 |
支持 |
|
|
|
|
支持 |
.NET到.NET的通信 |
|
支持 |
|
|
|
支持 |
分布式事務 |
|
|
支持 |
|
|
支持 |
支持WS標准 |
|
|
|
支持 |
|
支持 |
消息隊列 |
|
|
|
|
支持 |
支持 |
三、WCF簡單示例
1.建立解決方案
WCF.Host需引用WCF.Service,WCF.HostByWeb引用WCF.Service
2.WCF.Service項目:
IHelloWorldService.cs文件:
[ServiceContract(Namespace="www.cnblogs.com")] public interface IHelloWorldService { [OperationContract] string SayHello(string str); [OperationContract] Student Say(); } [DataContract] public class Student { [DataMember] public string UserName { get; set; } [DataMember] public int Age { get; set; } [DataMember] public GenderMode Gender { get; set; } } public enum GenderMode { Man = 1, Woman = 2, UnKnown = 3 }
HelloWorldService.cs
public class HelloWorldService : IHelloWorldService { public string SayHello(string str) { return "您說了:" + str; } public Student Say() { Student stu = new Student() { UserName = "zxj", Age = 20, Gender = GenderMode.Man }; return stu; } }
3.WCF.Host(以控制台程序作為宿主)
1.以配置文件的方式配置終結點
Program.cs文件
class Program { static void Main(string[] args) { ServiceHost host = new ServiceHost(typeof(WCF.Service.HelloWorldService)); Console.ForegroundColor = ConsoleColor.DarkYellow; host.Open(); Console.WriteLine("服務啟動成功......"); int i = 0; foreach (ServiceEndpoint endpoint in host.Description.Endpoints) { i++; Console.WriteLine("終結點序號:{0},終結點名稱:{1},終結點地址:{2},終結點綁定:{3}{4}",i, endpoint.Name, endpoint.Address, endpoint.Binding,Environment.NewLine); } Console.Read(); } }
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="WCF.Service.HelloWorldService"> <endpoint address="http://localhost:8000/HelloWorldService" contract="WCF.Service.IHelloWorldService" binding="wsHttpBinding"></endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint> <host> <baseAddresses> <add baseAddress="http://localhost:8000"/> </baseAddresses> </host> </service> </services> <behaviors> <serviceBehaviors> <behavior> <!-- 為避免泄漏元數據信息,請在部署前將以下值設置為 false --> <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/> <!-- 要接收故障異常詳細信息以進行調試,請將以下值設置為 true。在部署前設置為 false 以避免泄漏異常信息 --> <serviceDebug includeExceptionDetailInFaults="false"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> </configuration>
2.以編程方式配置終結點
class Program { static void Main(string[] args) { //編程方式配置終結點 Uri baseAddress = new Uri("http://localhost:8000"); ServiceHost host = new ServiceHost(typeof(WCF.Service.HelloWorldService), baseAddress); WSHttpBinding binding = new WSHttpBinding(); //尋找元數據 ServiceMetadataBehavior metadataBehavior = host.Description.Behaviors.Find<ServiceMetadataBehavior>(); //獲取宿主的行為列表 if (metadataBehavior == null)//如果沒有服務原數據交換的行為,實例化添加服務原數據交換行為 { metadataBehavior = new ServiceMetadataBehavior(); metadataBehavior.HttpGetEnabled = true; host.Description.Behaviors.Add(metadataBehavior); } host.AddServiceEndpoint(typeof(WCF.Service.IHelloWorldService), binding, "HelloWorldService"); host.AddServiceEndpoint(typeof(IMetadataExchange), binding , "mex"); Console.ForegroundColor = ConsoleColor.DarkYellow; host.Open(); Console.WriteLine("服務啟動成功......"); int i = 0; foreach (ServiceEndpoint endpoint in host.Description.Endpoints) { i++; Console.WriteLine("終結點序號:{0},終結點名稱:{1},終結點地址:{2},終結點綁定:{3}{4}", i, endpoint.Name, endpoint.Address, endpoint.Binding, Environment.NewLine); } Console.Read(); } }
4.WCF.Client(客戶端,控制台程序),需要添加System.Runtime.Serialization和System.ServiceModel引用
這里使用svcutil.exe,生成服務端代理類,使用方法如下:
Visual Studio ——>菜單欄——>工具——>外部工具
啟動宿主程序,最好使用右鍵——以管理員的身份打開控制台宿主程序
宿主程序啟動后,打開svcutil.exe程序,
Visual Studio ——>菜單欄——>工具——>SvcUtil(這是前一步配置外部工具時svcutil.exe的標題)
打開之后如圖所示,填入宿主元數據地址:
點擊確定,
如果你在配置外部工具時,選擇和我一樣的配置,你可以在解決方案根目錄下找到HelloWorldService.cs和output配置文件,將HelloWorldService.cs直接復制到WCF.Client項目中,打開output配置文件,將里面的內容復制到WCF.Client項目中App.config配置文件相應的地方
Program.cs
class Program { static void Main(string[] args) { HelloWorldServiceClient client = new HelloWorldServiceClient(); string temp = client.SayHello("你好!"); Console.WriteLine(temp); Student stu = client.Say(); Console.WriteLine("用戶名:" + stu.UserName + ",年齡:" + stu.Age + ",性別:" + stu.Gender); Console.Read(); } }
生成解決方案,先運行宿主控制台應用程序,再運行客戶端控制台程序,客戶端控制台程序結果如下圖所示:
至此,基於控制台應用程序的宿主相關示例已經結束。下面介紹,基於Web應用程序的宿主相關示例:
5.WCF.HostByWeb(宿主,Web程序)
新建“WCF 服務應用程序”,如圖所示:
添加對WCF.Service項目的引用,刪除IService1.cs,IService1.svc,新建WebHelloWorldService.svc頁面
刪除IWebHelloWorldService.cs和WebHelloWorldService.svc.cs文件,如圖:
打開WebHelloWorldService.svc:
<%@ ServiceHost Language="C#" Debug="true" Service="WcfService2.WebHelloWorldService" CodeBehind="WebHelloWorldService.svc.cs" %>
修改為:
<%@ ServiceHost Language="C#" Debug="true" Service="WCF.Service.HelloWorldService" %>
主要是Service="WCF.Service.HelloWorldService"。
右鍵WebHelloWorldService.svc,在瀏覽器中瀏覽:
這時我得到的網址為:http://localhost:32797/WebHelloWorldService.svc。
6.WCF.ClientByWeb項目(客戶端,控制台程序),需要添加System.Runtime.Serialization和System.ServiceModel引用
在這里與第4步一樣,也是使用svcutil.exe工具,根據URL地址生成對應的數據,可以直接參考第4步。
注意:本示例代碼,僅供參考不能用於實際開發。
源文件下載:WCF入門示例.rar