使用 NetHttpBindingUsing the NetHttpBinding

NetHttpBinding 是為了使用 HTTP 或 WebSocket 服務而設計的繫結,其預設會使用二進位編碼。NetHttpBinding is a binding designed for consuming HTTP or WebSocket services and uses binary encoding by default. NetHttpBinding 將會偵測其所搭配使用的是要求-回覆合約還是雙工合約,並改變行為來配合,也就是針對要求-回覆合約使用 HTTP,並針對雙工合約使用 WebSockets。NetHttpBinding will detect whether it is used with a request-reply contract or duplex contract and change its behavior to match - it will use HTTP for request-reply contracts and WebSockets for duplex contracts. 使用 WebSocketTransportUsage 設定即可覆寫這個行為:This behavior can be overridden using the WebSocketTransportUsage setting:

  1. Always- 這強制 WebSocket 甚至用於請求回復合同。Always - This forces WebSockets to be used even for request-reply contracts.

  2. Never- 這可以防止使用 WebSocket。Never - This prevents WebSockets from being used. 嘗試將這個設定用於雙工合約會導致例外狀況。Attempting to use a duplex contract with this setting will result in an exception.

  3. WhenDuplex- 這是預設值,行為情況如上所述。WhenDuplex - This is the default value and behaves as described above.

NetHttpBinding 在 HTTP 模式和 WebSocket 模式下都會支援可靠工作階段。NetHttpBinding supports reliable sessions in both HTTP mode and WebSocket mode. 在 WebSocket 模式中,工作階段是由傳輸提供。In WebSocket mode sessions are provided by the transport.

警告

當使用 NetHttpBinding 且繫結的 TransferMode 設為 TransferMode.Streamed 時,大量資料流可能會造成死結與呼叫逾時。When using the NetHttpBinding and the binding’s TransferMode is set to TransferMode.Streamed, large streams may cause a deadlock and the call will timeout. 為了解決此問題,請傳送較小的訊息或使用 TransferMode.Buffered。To work around this issue send smaller messages or use TransferMode.Buffered.

設定服務以使用 NetHttpBindingConfiguring a Service to use NetHttpBinding

可以將 NetHttpBinding 設定成和任何其他繫結程序一樣。The NetHttpBinding can be configured the same as any other binding. 下列組態檔片段說明如何使用 NetHttpBinding 來設定 WCF 服務。The following configuration snippet illustrates how to configure a WCF service with NetHttpBinding.

<system.serviceModel>  
    <services>  
      <service name="WcfService1.Service1">  
        <endpoint address=""  
                  binding="netHttpBinding"  
                  contract="WcfService1.IService1"/>  
        <endpoint address="mex"  
                  binding="mexHttpBinding"  
                  contract="IMetadataExchange"/>  
      </service>  
    </services>  
    <bindings>  
      <netHttpBinding>  
        <binding name="My_NetHttpBindingConfig">  
          <webSocketSettings transportUsage="WhenDuplex"/>  
        </binding>  
      </netHttpBinding>  
    </bindings>  
    ...
  </system.serviceModel>  

下列程式碼片段示範如何在程式碼中加入 NetHttpBindingThe following code snippet shows how to add the NetHttpBinding in code.

ServiceHost svchost = new ServiceHost(typeof(Service1), baseAddress);  
            NetHttpBinding binding = new NetHttpBinding();  
            svchost.AddServiceEndpoint(typeof(IService1), binding, address);
        }  

另請參閱See also