WCF 服務與客戶端皆大量依賴配置檔 (Web.config/App.config) 定義端點、繫結、行為。掌握 <system.serviceModel> 結構是 WCF 開發靈活性的關鍵。本文解析核心區段與三種宿主模式差異。
<system.serviceModel>
<services> <!-- 服務定義 -->
<service>
<endpoint/>
</service>
</services>
<bindings> <!-- 繫結集合 -->
<basicHttpBinding> ... </basicHttpBinding>
<customBinding> ... </customBinding>
</bindings>
<behaviors> <!-- 行為集合 -->
<serviceBehaviors> ... </serviceBehaviors>
<endpointBehaviors> ... </endpointBehaviors>
</behaviors>
<client> <!-- 客戶端端點 -->
</client>
</system.serviceModel>
<services>
<service name="WCFStudent.WCFStudentText" behaviorConfiguration="ServiceBehavior">
<endpoint address="" binding="wsHttpBinding" contract="WCFStudent.IStuServiceContract" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
name:服務實作類別完整名稱behaviorConfiguration:參考 <serviceBehaviors> 中的行為名稱endpoint:定義 Address (相對/絕對)、Binding、Contractaddress="":使用基底位址 (需在 Host 宣告 baseAddresses)<bindings>
<basicHttpBinding>
<binding name="IStuServiceContract"
closeTimeout="00:01:00" openTimeout="00:01:00"
receiveTimeout="00:10:00" sendTimeout="00:01:00"
maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
messageEncoding="Text" textEncoding="utf-8" ... />
</basicHttpBinding>
</bindings>
basicHttpBinding (相容 ASMX)、wsHttpBinding (WS-* 標準)、netTcpBinding (高效能內網)binding 元素以 name 識別,端點以 bindingConfiguration 參考timeout、encoding、security、readerQuotas、reliableSession 等<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true" /> <!-- 發布中繼資料 -->
<serviceDebug includeExceptionDetailInFaults="false" /> <!-- 例外詳細資訊 -->
</behavior>
</serviceBehaviors>
</behaviors>
serviceBehaviors:服務層級 (中繼資料、除錯、授權、節流、交易等)endpointBehaviors:端點層級 (序列化、驗證、路由等)<client>
<endpoint address="https://localhost:39113/WCFServiceText/WCFStudentText.svc"
binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IStuServiceContract"
contract="ServiceReference1.IStuServiceContract" name="WSHttpBinding_IStuServiceContract">
<identity><dns value="localhost" /></identity>
</endpoint>
</client>
| 宿主類型 | 配置檔名稱 | 備註 |
|---|---|---|
| IIS / WAS | Web.config | .svc 檔案指定 Service |
| Windows Service | App.config | 需在程式碼/配置宣告 baseAddresses |
| Self-Host (Console/WPF/WinForm) | App.config | 同 Windows Service |
結構大同小異,核心差異在基底位址宣告與啟動方式。
<configuration>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_IStuServiceContract" ...>
<security mode="Message">
<transport clientCredentialType="Windows" />
<message clientCredentialType="Windows" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<client> ... </client>
</system.serviceModel>
</configuration>
建議參考此標準輸出調整自訂配置。