HTTP Keep-alive和ServiceHost / C#?

时间:2011-04-15 08:27:09

标签: wcf

如何使用应用程序配置和C#ServiceHost启用/禁用HTTP Keep-alive并设置自托管服务的连接超时?

例如,

MyService service = new MyService();
ServiceHost serviceHost = new ServiceHost(service);
serviceHost.Open();

我需要在应用程序配置中放置什么来设置http keep alive和timeout。

<configuration>
  <system.serviceModel>
  <services>
    <service name="MyService" behaviorConfiguration="myServiceBehavior">
    <endpoint address="http://localhost:9005/"
          binding="webHttpBinding"
          contract="IMyService"
          behaviorConfiguration="myServerEndpointBehavior"/>
    </service>
  </services>
  </system.serviceModel>
  <!-- WHERE TO ENABLE/DISABLE http keep alive and timeout -->
</configuration>

如果您转到IIS管理器,则会找到IIS下的设置。右键单击“默认网站” - &gt;属性 - &gt;网站 - &gt;连接。我可以通过system.serviceModel配置来做到这一点吗?

1 个答案:

答案 0 :(得分:2)

默认情况下,http连接保持活动状态。如果要将其关闭,则必须创建自定义绑定:

<bindings>
    <customBinding>
        <binding name="WebHttpWithoutKeepAlive">
            <webMessageEncoding />
            <httpTransport keepAliveEnabled="false" />
        </binding>
    </customBinding>
</bindings>
<services>
    <service name="MyService" behaviorConfiguration="myServiceBehavior">
    <endpoint address="http://localhost:9005/"
          binding="customBinding"
          bindingConfiguration="WebHttpWithoutKeepAlive"
          contract="IMyService"
          behaviorConfiguration="myServerEndpointBehavior"/>
    </service>
</services>

How to set a keep-alive timout is a mystery。您的方案中没有“服务超时”(仅在与会话绑定时才有意义),保持活动超时不会中止客户端和服务之间的通信。

顺便说一下。您的示例代码将服务定义为singleton对象。