绑定和行为Binding and Behavior
绑定
简单的绑定定义描述了客户端是如何与服务端进行通信的,我们可以通过一个例子来理解。
想象一个场景,我将创建一个服务,有两种客户端需要来访问,一种是由HTTP通过SOAP来访问,另一种由TCP通过Binary来访问,如何实现这个服务端呢?通过Web Service的方式很难实现,但是通过WCF我们只需要在配置文件中添加一个终结点信息。
<system.serviceModel> <services> <service name="MathService" behaviorConfiguration="MathServiceBehavior"> <endpoint address="http://localhost:8090/MyService/MathService.svc" contract="IMathService" binding="wsHttpBinding"/> <endpoint address="net.tcp://localhost:8080/MyService/MathService.svc" contract="IMathService" binding="netTcpBinding"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="MathServiceBehavior"> <serviceMetadata httpGetEnabled="True"/> <serviceDebug includeExceptionDetailInFaults="true" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel>
在WCF中就这么简单,微软将复杂的事情变的简单了。通过行为的作用范围区分,通用的行为影响所有的终结点,服务本身的行为影响改服务本身,终结点行为只影响终结点相关,操作级别的行为影响特定的操作
示例
下面是一个配置示例,我提到过服务作用域范围的行为,在此行为描述中有servieMetadata这个节点,并且它的一个属性是httGetEnabled='true',这个属性指示了服务元数据是否被公布,相似的我们可以添加更多行为。
<system.serviceModel> <services> <service name="MathService" behaviorConfiguration="MathServiceBehavior"> <endpoint address="" contract="IMathService" binding="wsHttpBinding"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="MathServiceBehavior"> <serviceMetadata httpGetEnabled="True"/> <serviceDebug includeExceptionDetailInFaults="true" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel>
注意
配置可以通过硬编码或者文件的方式进行,硬编码的方式可以覆盖使用配置文件的方式。