關于WCF服務元數據交換編程揭密
WCF還是比較常用的,于是我研究了一下WCF服務元數據交換,在這里拿出來和大家分享一下,希望對大家有用。前者配置簡單、快捷,后者相對復雜。但是編程方式允許代碼運行時控制或者設置元數據交換的信息。因而更加靈活。下面我們就來看看如何通過代碼實現剛才的服務原數據交換的配置。
WCF服務元數據交換HTTP-GET編程實現:
必須添加對命名空間的引用, using System.ServiceModel.Description;我們對服務元數據操作的類和接口信息定義在此命名空間里,具體的實現HTTP-GET的代碼如下:
- ServiceMetadataBehavior metadataBehavior;
- //定義服務行為變量,
- metadataBehavior = host.Description.Behaviors.Find<ServiceMetadataBehavior>();
- //獲取宿主的行為列表
- if (metadataBehavior == null)
- //如果沒有服務原數據交換的行為,實例化添加服務原數據交換行為
- {
- metadataBehavior = new ServiceMetadataBehavior();
- Uri httpAddress = new Uri("http://localhost:8001/");
- metadataBehavior.HttpGetUrl =httpAddress;
- metadataBehavior.HttpGetEnabled = true;//設置HTTP方式
- host.Description.Behaviors.Add(metadataBehavior);
- }
#T#首先是獲得服務行為的列表信息,如果沒有設置,我們就進行實例化服務原數據交換行為,并設置http方式可用。 host.Description.Behaviors.Add(metadataBehavior);添加宿主服務的行為。
WCF服務元數據交換WS-*編程實現:
這里分別實現了HTTP、TCP、IPC三種方式的的元數據交換的代碼。和http-get方式略有不同,我們需要實例化自己綁定元素和綁定,***作為參數傳遞給host宿主實例。具體實現代碼如下:
- //2編程方式實現ws*原數據交換
- //生命三個綁定節點類
- BindingElement tcpBindingElement = new TcpTransportBindingElement();
- BindingElement httpBindingElement = new HttpsTransportBindingElement();
- BindingElement pipeBindingElement = new NamedPipeTransportBindingElement();
- //實例化通用綁定類的實例
- Binding tcpBinding = new CustomBinding(tcpBindingElement);
- Binding httpBinding = new CustomBinding(httpBindingElement);
- Binding pipeBinding = new CustomBinding(pipeBindingElement);
- //
- Uri tcpBaseAddress = new Uri("net.tcp://localhost:9001/");
- Uri httpBaseAddress = new Uri("http://localhost:9002/");
- Uri pipeBaseAddress = new Uri("net.pipe://localhost/");
- host.AddServiceEndpoint(typeof(WCFService.IWCFService), new NetTcpBinding(), tcpBaseAddress);
- host.AddServiceEndpoint(typeof(WCFService.IWCFService), new WSHttpBinding(), httpBaseAddress);
- host.AddServiceEndpoint(typeof(WCFService.IWCFService), new NetNamedPipeBinding(), pipeBaseAddress);
- //ServiceMetadataBehavior metadataBehavior;//定義服務行為變量,
- metadataBehavior = host.Description.Behaviors.Find<ServiceMetadataBehavior>();
- //獲取宿主的行為列表
- if (metadataBehavior == null)//如果沒有服務原數據交換的行為,實例化添加服務原數據交換行為
- {
- metadataBehavior = new ServiceMetadataBehavior();
- host.Description.Behaviors.Add(metadataBehavior);
- }
- //如果沒有可用的mex節點,可以使用一下代碼判斷,添加mex節點
- host.AddServiceEndpoint(typeof(IMetadataExchange), tcpBinding, "mex");
- host.AddServiceEndpoint(typeof(IMetadataExchange), httpBinding, "mex");
- host.AddServiceEndpoint(typeof(IMetadataExchange), pipeBinding, "mex");