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