剖析WCF配置全過程
如果WCF配置為空,那么endpoint的地址就是默認的基地址(Base Address)。例如WCF配置的地址就是http://localhost/servicemodelsamples/service.svc,而IMetadataExchange服務的地址則為http://localhost/servicemodelsamples/service.svc/mex。這里所謂的基地址可以在<service>中通過配置<host>來定義:
- <service
- name="Microsoft.ServiceModel.Samples.CalculatorService"
- behaviorConfiguration="CalculatorServiceBehavior">
- <host>
- <baseAddresses>
- <add baseAddress=
- "http://localhost/ServiceModelSamples/service.svc"/>
- </baseAddresses>
- </host>
- <endpoint … />
- </service>
當我們在定義一個實現了Service Contract的類時, binding和address信息是客戶端必須知道的,否則無法調用該服務。然而,如果需要指定服務在執(zhí)行方面的相關特性時,就必須定義服務的behavior。在WCF中,定義behavior就可以設置服務的運行時屬性,甚至于通過自定義behavior插入一些自定義類型。例如通過指定ServiceMetadataBehavior,可以使WCF服務對外公布Metadata。WCF配置如下:
- <behaviors>
- <serviceBehaviors>
- <behavior name="metadataSupport">
- <serviceMetadata httpGetEnabled="true" httpGetUrl=""/>
- </behavior>
- <serviceBehaviors>
- <behaviors>
在WCF配置中,behavior被定義為Attribute,其中,System.ServiceModel.ServiceBehaviorAttribute和System.ServiceModel.OperationBehaviorAttribute是最常用的behavior。雖然,behavior作為Attribute可以通過編程的方式直接施加到服務上,但出于靈活性的考慮,將behavior定義到WCF配置文件中才是***的設計方式。#t#
利用ServiceBehavior與OperationBehavior可以控制服務的如下屬性:
- <behaviors>
- <serviceBehaviors>
- <behavior name="metadataSupport">
- <instanceContextMode httpGetEnabled="true" httpGetUrl=""/>
- </behavior>
- <serviceBehaviors>
- <behaviors>