Using the NetHttpBinding

NetHttpBinding is a binding designed for consuming HTTP or WebSocket services and uses binary encoding by default. 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. This behavior can be overridden using the WebSocketTransportUsage setting:

  1. Always - This forces WebSockets to be used even for request-reply contracts.

  2. Never - This prevents WebSockets from being used. Attempting to use a duplex contract with this setting will result in an exception.

  3. WhenDuplex - This is the default value and behaves as described above.

NetHttpBinding supports reliable sessions in both HTTP mode and WebSocket mode. In WebSocket mode sessions are provided by the transport.


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. To work around this issue send smaller messages or use TransferMode.Buffered.

Configuring a Service to use NetHttpBinding

The NetHttpBinding can be configured the same as any other binding. The following configuration snippet illustrates how to configure a WCF service with NetHttpBinding.

      <service name="WcfService1.Service1">  
        <endpoint address=""  
        <endpoint address="mex"  
        <binding name="My_NetHttpBindingConfig">  
          <webSocketSettings transportUsage="WhenDuplex"/>  

The 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