WCF 服務的所有通訊皆透過服務端點進行。每個端點包含三大核心要素:位址、繫結、合約,即經典的「ABC」模型。合約定義可用操作,繫結指定通訊協定與編碼,位址則指出服務所在位置。WCF 以多種通訊協靈活支援服務發布與互通。本系列第一部分將圍繞端點定址細節展開,先簡要回顧 WCF 程式設計模型(如圖 1)。

圖 1:WCF 程式設計模型示意
WCF 的端點位址遵循 WS-Addressing 規範,以端點參考(Endpoint Reference, EPR)為模型。為何需要此規範?主要三大動機:

圖 2:複雜交互模式示意
WS-Addressing 核心只有兩個概念:端點參考與訊息資訊標頭。以下範例展示一則 SOAP 1.2 訊息發送至 https://fabrikam123.com/Purchasing:
<S:Envelope xmlns:S="https://www.w3.org/2002/12/soap-envelope"
xmlns:wsa="https://schemas.xmlsoap.org/ws/2003/03/addressing">
<S:Header>
<wsa:ReplyTo>
<wsa:Address>https://business456.com/client1</wsa:Address>
</wsa:ReplyTo>
<wsa:To>https://fabrikam123.com/Purchasing</wsa:To>
<wsa:Action>https://fabrikam123.com/SubmitPO</wsa:Action>
</S:Header>
<S:Body>......</S:Body>
</S:Envelope>
Web 服務端點是可被參考的實體、處理器或資源。端點參考傳達識別或參考端點所需的資訊,用途多樣:可用於傳達存取端點所需資訊,也可在服務間往返的訊息中提供定址。其資訊集結構如下:
<wsa:EndpointReference>
<wsa:Address>xs:anyURI</wsa:Address>
<wsa:ReferenceProperties>...</wsa:ReferenceProperties>?
<wsa:ReferenceParameters>...</wsa:ReferenceParameters>?
<wsa:PortType>xs:QName</wsa:PortType>?
<wsa:ServiceName PortName="xs:NCName"?>xs:QName</wsa:ServiceName>?
<wsa:Policies>...</wsa:Policies>?
<xs:any/>*
</wsa:EndpointReference>
簡單來說,端點參考就是用 XML 元素包裝的 URL,例如:
<wsa:myLocation>
<wsa:Address>https://localhost:8887/CalculatorService</wsa:Address>
</wsa:myLocation>
此處 wsa:myLocation 即為端點參考,內部 wsa:Address 指定存取服務的實際位址。每個端點參考可包含提供額外識別資訊的參考參數。
訊息資訊標頭是 WS-Addressing 定義的標準 SOAP 標頭擴展,用於攜帶訊息傳遞相關資訊。不同於端點參考,它直接內嵌於 SOAP Header 中。其資訊集包含:
<wsa:To>xs:anyURI</wsa:To>?
<wsa:From>wsa:EndpointReferenceType</wsa:From>?
<wsa:ReplyTo>wsa:EndpointReferenceType</wsa:ReplyTo>?
<wsa:FaultTo>wsa:EndpointReferenceType</wsa:FaultTo>?
<wsa:Action>xs:anyURI</wsa:Action>
<wsa:MessageID>xs:anyURI</wsa:MessageID>?
<wsa:RelatesTo RelationshipType="xs:anyURI"?>xs:anyURI</wsa:RelatesTo>*
<wsa:ReferenceParameters>xs:any*</wsa:ReferenceParameters>?
各標頭用途說明:
<wsa:Address> 值一致。<wsa:Action>https://tempuri.org/ICalculator/Add</wsa:Action> 表示呼叫 Add 方法。圖 3 以視覺化方式展示訊息資訊標頭與 SOAP 結構的關係:

圖 3:訊息資訊標頭與 SOAP 結構關係圖
WS-Addressing 規範完整內容請參考 W3C 提交文件。
現在建立一個簡單 WCF 服務並攔截訊息,觀察其如何符合 WS-Addressing:
[ServiceContract]
public interface ICalculator
{
[OperationContract]
int Add(int x, int y);
}
public class CalculatorService : ICalculator
{
public int Add(int x, int y) { return x + y; }
}
使用追蹤診斷攔截 SOAP 訊息,可見標頭中的 To 位址與 Action(對應 Add 方法)以及 Body 內容:
<s:Envelope xmlns:s="https://schemas.xmlsoap.org/soap/envelope/">
<s:Header>
<To s:mustUnderstand="1">https://localhost:8887/CalculatorService</To>
<Action s:mustUnderstand="1">https://tempuri.org/ICalculator/Add</Action>
</s:Header>
<s:Body>
<Add xmlns="https://tempuri.org/">
<x>1</x>
<y>2</y>
</Add>
</s:Body>
</s:Envelope>
WS-Addressing 為 Web 服務世界帶來統一定址標準,透過端點參考與訊息資訊標頭提供一致機制。下一篇將繼續深入分析 WCF 定址實作細節。