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

时间:2019-08-15 23:20:59

标签: c# .net wcf https webservicehost

我在这里读过some posts,声称WCF可以在同一端点/端口上允许http和https,但这听起来有点不对劲。我尝试进行设置,但无法弄清楚如何在相同的端口/ ip(编程方式)上同时启用https和http侦听。

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

  

'System.ServiceModel.AddressAlreadyInUseException'在   System.ServiceModel.dll HTTP无法注册URL   https://+:10901/Service/。另一个应用程序已经   在HTTP.SYS中注册了此URL。

如果我只添加其中之一,效果很好。

代码:

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可以托管在同一端口上呢?我读错了吗,实际上是不可能的? =)

1 个答案:

答案 0 :(得分:0)

我不确定这是您想要的。但我只是继续发布我的答案。 在单个端口上同时托管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>