[ServiceContract]
public interface IHelloWCF {
[OperationContract]
void Say(string input);
}
Uri address = new Uri("https://localhost:4000/IHelloWCF");
BasicHttpBinding binding = new BasicHttpBinding();
ServiceHost svc = new ServiceHost(typeof(HelloWCF));
svc.AddServiceEndpoint(typeof(IHelloWCF), binding, address);
svc.Open();
Console.WriteLine("Receiving application ready");
Console.ReadLine();
svc.Close();
public class HelloWCF : IHelloWCF {
public void Say(string input) {
Console.WriteLine("Message received: {0}", input);
}
}
csc /r:System.ServiceModel.dll HelloWCFApp.cs
HelloWCFApp.exe
netstat -a -b // 確認 4000 埠監聽
ChannelFactory<IHelloWCF> factory = new ChannelFactory<IHelloWCF>(binding, new EndpointAddress(address));
IHelloWCF proxy = factory.CreateChannel();
proxy.Say("Hi there WCF");
ChannelFactory<T> 建構發送管線,CreateChannel() 回傳實作服務契約的透明 Proxy。EndpointAddress 而非 Uri,符合 WS-Addressing 標準。public void Say(string input) {
Console.WriteLine("Body: {0}", input);
Console.WriteLine(OperationContext.Current.RequestContext.RequestMessage.ToString());
}
BasicHttpBinding 產生簡單 SOAP 1.1 訊息。
改為 WSHttpBinding 後,訊息包含 WS-Addressing、WS-Security、WS-SecureConversation、Timestamp、加密資料等完整 WS-* 標頭,結構龐大複雜。
單行繫結變更即改變整個訊息協定堆疊,體現 WCF 「簡單物件模型」下隱藏的訊息導向本質。
ServiceMetadataBehavior,設 HttpGetEnabled=true。MetadataExchangeBindings.CreateMexTcpBinding() + net.tcp://localhost:5000/IHelloWCF/Mex 端點,契約為 IMetadataExchange。svcutil.exe /target:code net.tcp://localhost:5000/IHelloWCF/Mex 產生 HelloWCFProxy.cs、output.config。HelloWCFClient 呼叫服務,無需共用組件。WCF 宏觀編程模型隱藏訊息細節,提供分布式物件錯覺。開發者必須理解繫結變更如何影響訊息結構,並在部署前關閉中繼資料發布與例外詳細資訊。