簡體   English   中英

基於 IIS 綁定將 WCF 端點動態綁定到 HTTPS

[英]Dynamically Bind WCF Endpoints To HTTPS Based on IIS Bindings

我有一個 WCF 服務,我正在將它從 HTTP 轉換為 HTTPS。 客戶端當前具有該服務的硬編碼 HTTP URL。 服務器使用 Web.config 文件中的一些自定義行為綁定服務:

  <service behaviorConfiguration="MyServiceBehaviors" name="MyService">
    <endpoint address="" behaviorConfiguration="MyEndpointBehaviors" binding="customBinding" bindingConfiguration="MyHttpCustomBinding" name="MyService" contract="IMyService" />
  </service>

我想將 WCF 服務綁定到 HTTP 和 HTTPS。 我可以使用 Web.config 文件中的兩個條目執行此操作:

  <service behaviorConfiguration="MyServiceBehaviors" name="MyService">
    <endpoint address="" behaviorConfiguration="MyEndpointBehaviors" binding="customBinding" bindingConfiguration="MyHttpCustomBinding" name="MyService" contract="IMyService" />
    <endpoint address="" behaviorConfiguration="MyEndpointBehaviors" binding="customBinding" bindingConfiguration="MyHttpsCustomBinding" name="MyService" contract="IMyService" />
  </service>

我還要求服務器一開始可能沒有啟用 HTTPS。 所以IIS在WCF服務激活時可能沒有綁定HTTPS端口443。

如果 IIS綁定到 HTTPS,並且 Web.config 像上面的示例一樣綁定到兩個終結點,並且客戶端嘗試在 HTTP 終結點上激活該服務,則該服務將無法啟動並出現以下激活異常:

WebHost 無法處理請求。 發件人信息:System.ServiceModel.ServiceHostingEnvironment+HostingManager/45653674 異常:System.ServiceModel.ServiceActivationException:由於編譯期間出現異常,無法激活服務“/MyApp/MyService.svc”。 異常消息是:找不到與具有綁定 CustomBinding 的端點的方案 https 匹配的基地址。 注冊的基地址方案是 [http]。

我認為只有在 IIS 中啟用 HTTPS 時,WCF 服務才需要綁定到 HTTPS。 我在 Web.config 文件中看不到實現此目的的方法,因此我假設我需要進行一些動態服務器綁定。

如何根據 IIS 配置有選擇地綁定 WCF 中的 HTTP 和 HTTPS 端點?

如果 IIS 綁定更改為添加/刪除 HTTPS,我也沒有看到可以通知服務的方式,但我可以要求管理員回收應用程序池/IISRESET/重啟以使服務使用更新的設置。

我能夠通過以下步驟使其工作:

將 Factory 屬性添加到 MyService.svc 文件中,以便能夠構建服務:

<%@ ServiceHost Language="C#" Debug="true"
    Service="MyService"
    Factory="MyServiceFactory" %>

在 WCF 服務 DLL 中創建工廠類:

public class MyServiceFactory : ServiceHostFactory
{
    public override ServiceHostBase CreateServiceHost(string service, Uri[] baseAddresses)
    {
        return CreateServiceHost(typeof(MyService), baseAddresses);
    }

    protected override ServiceHost CreateServiceHost(Type t, Uri[] baseAddresses)
    {
        var serviceHost = new ServiceHost(t, baseAddresses);
        foreach (Uri address in baseAddresses)
        {
            bool secure = false;
            if (address.Scheme == "https")
                secure = true;

            var binding = GetMyCustomBinding(secure);
            var endpoint = serviceHost.AddServiceEndpoint(typeof(IMyService), binding, address);

            endpoint.Behaviors.Add(new MyEndpointBehavior());
        }

        return serviceHost;
    }
}

給定的 baseAddresses 數組包括綁定 IIS 的端點 Uris。 對於每個端點,使用自定義綁定將服務綁定到端點。 如果端點是“https”,則使用安全綁定; 否則,使用標准綁定。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM