WCF:以编程方式在同一 ip/port 上同时启用 https 和 http

WCF: Programmatically enable both https and http on same ip/port

我在这里读过 some posts,声称 WCF 可以在同一个 endpoint/port 上允许 http 和 https,但这对我来说听起来有点不对。我试图设置它,但我无法弄清楚如何启用 https 和 http 侦听相同的 port/ip、programmtically.

我尝试添加 https 时出现以下错误:

'System.ServiceModel.AddressAlreadyInUseException' in System.ServiceModel.dll HTTP could not register URL https://+:10901/Service/. Another application has already registered this URL with HTTP.SYS.

如果我只添加其中一个就可以正常工作。

代码:

Uri httpsUri = new Uri("https://" + localIp.ToString() + ":" + settings._WebservicePort.ToString() + "/Service/");
Uri httpUri = new Uri("http://" + localIp.ToString() + ":" + settings._WebservicePort.ToString() + "/Service/");

host = new WebServiceHost(typeof(Service), httpUri, httpsUri);

WebHttpBinding whbHttp = new WebHttpBinding
{
    CrossDomainScriptAccessEnabled = true,
    Security = { Mode = WebHttpSecurityMode.None },
    MaxReceivedMessageSize = 10000000
};

WebHttpBinding whbHttps = new WebHttpBinding
{
    CrossDomainScriptAccessEnabled = true,
    Security = { Mode = WebHttpSecurityMode.Transport },
    MaxReceivedMessageSize = 10000000
};
ServiceEndpoint seHttp = host.AddServiceEndpoint(typeof(IService), whbHttp, httpUri);
seHttp.Behaviors.Add(new WebHttpBehavior());

ServiceEndpoint seHttps = host.AddServiceEndpoint(typeof(IService), whbHttps, httpsUri);
seHttps.Behaviors.Add(new WebHttpBehavior());

ServiceDebugBehavior stp = host.Description.Behaviors.Find<ServiceDebugBehavior>();
stp.HttpHelpPageEnabled = true;

host.Open(); // <-- Exception: 'System.ServiceModel.AddressAlreadyInUseException' in System.ServiceModel.dll HTTP could not register URL https://+:10901/Service/. Another application has already registered this URL with HTTP.SYS.

我知道 Web http 是端口 80,而 https 通常是 443,但为什么我读到 http 和 https 可以托管在同一端口上?我是不是看错了,这实际上是不可能的? =)

我不确定这是否是您想要的。但我只是继续 post 我的回答。 在单个端口上同时托管 http 和 https 是不可能的。但您可以像这样同时拥有 http 和 https 绑定:

<bindings>
      <webHttpBinding>
        <binding name="RestBinding"/>
        <binding name="SecureRestBinding" >
          <security mode="Transport"/>
        </binding>
      </webHttpBinding>
    </bindings>
    <services>
      <service behaviorConfiguration="ServiceBehavior" name="YOURPROJECT.YOURSERVICE">
        <endpoint address="" behaviorConfiguration="Web" binding="webHttpBinding" bindingConfiguration="RestBinding" name="Rest" contract="YOURPROJECT.IYOURSERVICE"/>
        <endpoint address="" behaviorConfiguration="Web" binding="webHttpBinding" bindingConfiguration="SecureRestBinding" name="SecureRest" contract="YOURPROJECT.IYOURSERVICE"/>
      </service>
    </services>