在Windows服务中承载HTTP WCF服务

时间:2017-08-02 09:47:44

标签: c# wcf http

我在Windows服务中托管HTTP WCFService,在本地网络中它运行良好,但如果客户端在另一个网络中并尝试与de public IP连接则无效。

配置文件:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" />
  </system.web>
  <!-- When deploying the service library project, the content of the config              
  file must be added to the host's 
  app.config file. System.Configuration does not support config files for         
  libraries. -->
  <system.serviceModel>
    <services>
      <service name="WCFService.ServiceBehavior">
        <endpoint address="" binding="wsHttpBinding"     
          contract="WCFService.ServiceContract">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" 
        contract="IMetadataExchange" />
    <host>
      <baseAddresses>
        <add baseAddress="http://localhost:80/WCFService/service/" />
      </baseAddresses>
    </host>
  </service>
</services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, 
          set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="True" httpsGetEnabled="True"/>
      <serviceDebug includeExceptionDetailInFaults="False" />
    </behavior>
  </serviceBehaviors>
</behaviors>
  </system.serviceModel>

</configuration>

2 个答案:

答案 0 :(得分:1)

服务元数据将 http:// localhost:80 / WCFService / service / 发布到客户端。无法从本地主机外部访问此URL。

为了使用公共IP从其他网络访问服务,服务元数据应将 http:// PUBLIC_IP_ADDRESS / WCFService / service / 发布到客户端。这可以根据客户端使用的URL动态完成。只需将 useRequestHeadersForMetadataAddress 添加到服务行为。

<behaviors>
    <serviceBehaviors>
       <behavior name="...">
         ...
         <useRequestHeadersForMetadataAddress />
       </behavior>
    </serviceBehaviors>
</behaviors>

请参阅Auto-resolving a hostname in WCF Metadata Publishing

答案 1 :(得分:0)

我怀疑当你给出这样的配置时:

<add baseAddress="http://localhost:80/WCFService/service/" />

由于使用 locahost ,它会在环回地址中侦听。将其更改为实际的公共IP地址(即,不是127.0.0.1)或服务器名称,然后再次检查。