基于IIS绑定将WCF端点动态绑定到HTTPS

问题描述 投票:0回答:1

我有一个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。因此,在激活WCF服务时,IIS可能未绑定到HTTPS端口443。

如果IIS是not绑定到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 /重新启动以使服务使用更新后的方法设置。

c# wcf iis wcf-binding
1个回答
0
投票

我能够通过以下步骤使它起作用:

  1. 向MyService.svc文件添加Factory属性:

  2. 创建工厂类:

    公共类MyServiceFactory:ServiceHostFactory{公共重写ServiceHostBase CreateServiceHost(字符串服务,Uri [] baseAddresses){返回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;
    }
    

    }

© www.soinside.com 2019 - 2024. All rights reserved.