使用Service Fabric的SOAP - Https和Http绑定

21

我目前正在开发一个服务织物应用程序,该应用程序将公开一个SOAP监听器,该监听器将被另一个应用程序使用

我一直收到一个错误,说

找不到与自定义绑定的端点匹配的基本地址的方案https。 注册的基本地址方案为[]

以下是CreateServiceInstanceListener方法

protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
    {
        var serviceInstanceListers = new List<ServiceInstanceListener>()
        {
            new ServiceInstanceListener(context =>
            {
                return CreateSoapListener(context);
            })
            ,
            new ServiceInstanceListener(context =>
            {
                return CreateSoapHTTPSListener(context);
            }),
        };
        return serviceInstanceListers;
    }


    private static ICommunicationListener CreateSoapHTTPSListener(StatelessServiceContext context)
    {
        string host = context.NodeContext.IPAddressOrFQDN;
        var endpointConfig = context.CodePackageActivationContext.GetEndpoint("SecureServiceEndpoint");
        int port = endpointConfig.Port;
        string scheme = endpointConfig.Protocol.ToString();

        string uri = string.Format(CultureInfo.InvariantCulture, "{0}://{1}:{2}/MyService/", scheme, host, port);
        var listener = new WcfCommunicationListener<IServiceInterface>(
            serviceContext: context,
            wcfServiceObject: new Service(),
            listenerBinding: new BasicHttpsBinding(BasicHttpsSecurityMode.Transport),
            address: new EndpointAddress(uri)
        );

        // Check to see if the service host already has a ServiceMetadataBehavior
        ServiceMetadataBehavior smb = listener.ServiceHost.Description.Behaviors.Find<ServiceMetadataBehavior>();
        // If not, add one
        if (smb == null)
        {
            smb = new ServiceMetadataBehavior();
            smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
            smb.HttpsGetEnabled = true;
            smb.HttpsGetUrl = new Uri(uri);

            listener.ServiceHost.Description.Behaviors.Add(smb);
        }
        return listener;
    }

    private static ICommunicationListener CreateSoapListener(StatelessServiceContext context)
    {
        string host = context.NodeContext.IPAddressOrFQDN;
        var endpointConfig = context.CodePackageActivationContext.GetEndpoint("ServiceEndpoint");
        int port = endpointConfig.Port;
        string scheme = endpointConfig.Protocol.ToString();

        string uri = string.Format(CultureInfo.InvariantCulture, "{0}://{1}:{2}/MyService/", scheme, host, port);
        var listener = new WcfCommunicationListener<IServiceInterface>(
            serviceContext: context,
            wcfServiceObject: new Service(),
            listenerBinding: new BasicHttpBinding(BasicHttpSecurityMode.None),
            address: new EndpointAddress(uri)
        );

        // Check to see if the service host already has a ServiceMetadataBehavior
        ServiceMetadataBehavior smb = listener.ServiceHost.Description.Behaviors.Find<ServiceMetadataBehavior>();
        // If not, add one
        if (smb == null)
        {
            smb = new ServiceMetadataBehavior();
            smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
            smb.HttpGetEnabled = true;
            smb.HttpGetUrl = new Uri(uri);

            listener.ServiceHost.Description.Behaviors.Add(smb);
        }
        return listener;
    }

以下是 app.config 文件(如果有无用条目,抱歉,我是从现有的 WCF 应用程序中复制的)

    <?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2"/>
  </startup>

  <system.web>
    <customErrors mode="On"></customErrors>
    <compilation debug="true" targetFramework="4.6.2"/>
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"/>
    </httpModules>
    <machineKey decryption="AES" decryptionKey="decryptionkey" validation="SHA1" validationKey="validationkey"/>
  </system.web>
  <system.serviceModel>
    <diagnostics wmiProviderEnabled="true">
      <messageLogging logEntireMessage="true" logKnownPii="true" logMalformedMessages="true" logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="true"/>
      <endToEndTracing propagateActivity="true" activityTracing="true" messageFlowTracing="true"/>
    </diagnostics>
    <bindings>
      <customBinding>
        <binding name="HubBinding">
          <security defaultAlgorithmSuite="Basic256Sha256Rsa15" allowSerializedSigningTokenOnReply="true" authenticationMode="MutualCertificateDuplex" securityHeaderLayout="Lax" messageProtectionOrder="EncryptBeforeSign" messageSecurityVersion="WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10"/>
          <textMessageEncoding messageVersion="Default"/>
          <httpsTransport maxReceivedMessageSize="1073741824"/>
        </binding>
        <binding name="AuthorityCustomBinding">
          <security defaultAlgorithmSuite="Basic256Sha256Rsa15" allowSerializedSigningTokenOnReply="true" authenticationMode="MutualCertificateDuplex" securityHeaderLayout="Lax" messageProtectionOrder="EncryptBeforeSign" messageSecurityVersion="WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10"/>
          <textMessageEncoding messageVersion="Default"/>
          <httpsTransport maxReceivedMessageSize="1073741824"/>
        </binding>
        <binding name="CustomBinding_IServiceInterface">
          <security/>
          <textMessageEncoding/>
          <httpsTransport/>
        </binding>

      </customBinding>
    </bindings>
    <services>
      <service name="MyApp.ProductServiceManufacturer" behaviorConfiguration="ManufacturerBehaviour">
        <endpoint address="" name="ManufacturerProductService" binding="customBinding" bindingConfiguration="HubBinding" contract="MyApp.IProductServiceV20161"/>
      </service>

    </services>
    <client>
      <endpoint address="https://serverurl:8088/IServiceInterface/Service.svc" behaviorConfiguration="HubManufacturerBehavior" binding="customBinding" bindingConfiguration="AuthorityCustomBinding" contract="Service.IServiceInterface" name="CustomBinding_IProductServiceManufacturerV20161">
        <identity>
          <dns value="ServerCert"/>
        </identity>
      </endpoint>

    </client>
    <behaviors>
      <endpointBehaviors>
        <behavior name="HubManufacturerBehavior">
          <clientCredentials>
            <clientCertificate findValue="XXXXXX" storeLocation="LocalMachine" storeName="My" x509FindType="FindByThumbprint"/>
            <serviceCertificate>
              <defaultCertificate findValue="XXXXXX" storeLocation="LocalMachine" storeName="My" x509FindType="FindByThumbprint"/>
            </serviceCertificate>
          </clientCredentials>
        </behavior>
        <behavior name="MyApp.ReportingServiceManufacturerAspNetAjaxBehavior">
          <enableWebScript/>
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="ManufacturerBehaviour">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
          <serviceCredentials>
            <serviceCertificate findValue="XXXXXX" storeLocation="LocalMachine" storeName="My" x509FindType="FindByThumbprint"/>
          </serviceCredentials>
          <serviceSecurityAudit auditLogLocation="Application" suppressAuditFailure="true" serviceAuthorizationAuditLevel="Failure" messageAuthenticationAuditLevel="Failure"/>
        </behavior>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
    <extensions>
      <bindingElementExtensions>
        <add name="securityBindingElementExtension" type="MyApp.BindingExtensions.SecurityBindingElementExtension, MyApp"/>
      </bindingElementExtensions>
    </extensions>
    <protocolMapping>
      <add binding="basicHttpsBinding" scheme="http"/>
      <add binding="customBinding" scheme="https"/>
    </protocolMapping>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="TelemetryCorrelationHttpModule"/>
      <add name="TelemetryCorrelationHttpModule" type="Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule, Microsoft.AspNet.TelemetryCorrelation" preCondition="integratedMode,managedHandler"/>
      <remove name="ApplicationInsightsWebTracking"/>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler"/>
    </modules>


    <directoryBrowse enabled="true"/>
    <validation validateIntegratedModeConfiguration="false"/>
  </system.webServer>
</configuration>

我做错了什么或代码缺失了什么? 由于我以前从未使用过WCF,因此任何帮助都将不胜感激。 顺便说一下,当在服务器上部署时,WCF应用程序与相同的配置一起工作,但如果您想知道为什么我正在使用服务织物,那不是我的问题 :)
更新 考虑到LoekD的答案,我更新了我的CreateSoapHTTPSListener方法,这是它的样子:
private static ICommunicationListener CreateSoapHTTPSListener(StatelessServiceContext context)
    {
        string host = context.NodeContext.IPAddressOrFQDN;
        var endpointConfig = context.CodePackageActivationContext.GetEndpoint("SecureServiceEndpoint");
        int port = endpointConfig.Port;
        string scheme = endpointConfig.Protocol.ToString();
        var binding = new BasicHttpsBinding(BasicHttpsSecurityMode.Transport);
        binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
        binding.MaxReceivedMessageSize = 1073741824;

        string uri = ConfigurationManager.AppSettings.Get("ProductManufacturerService");
        Tools.TraceMessage(uri);
        var listener = new WcfCommunicationListener<IProductServiceV20161>(
            serviceContext: context,
            wcfServiceObject: new ProductServiceManufacturer(),
            listenerBinding: binding,
            address: new EndpointAddress(uri)
        );
        listener.ServiceHost.Credentials.ServiceCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindByThumbprint, ConfigurationManager.AppSettings.Get("ServiceCertificateThumbprint"));
        listener.ServiceHost.Credentials.ClientCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindByThumbprint, ConfigurationManager.AppSettings.Get("ClientCertificateThumbprint"));

        // Check to see if the service host already has a ServiceMetadataBehavior
        ServiceMetadataBehavior smb = listener.ServiceHost.Description.Behaviors.Find<ServiceMetadataBehavior>();
        // If not, add one
        if (smb == null)
        {
            smb = new ServiceMetadataBehavior();
            smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
            smb.HttpsGetEnabled = true;
            smb.HttpGetEnabled = false;
            smb.HttpsGetUrl = new Uri(uri);
            listener.ServiceHost.Description.Behaviors.Add(smb);
        }
        return listener;
    }

然后我收到一个错误,内容如下:
{{服务包含多个ServiceEndpoints,每个Endpoint都有Name ='IProductServiceV20161'和Namespace ='namespaceurl /'的ContractDescriptions不同。}}
我猜这是因为在app.config文件和.cs文件中都定义了服务端点,我注释了app.config中的端点标签,然后它就正常工作了。但是,与WCF应用程序获取的文件相比,我获取的wsdl文件缺少一些条目。 更新2:如何为服务指定端点标识?是否可以使用自定义BindingElementExtensionElement类?
3个回答

8

请确保服务清单中的终结点声明为“HTTPS”类型,并将SSL证书添加到WCF服务主机。

您可以尝试更改以下内容:

listenerBinding: new BasicHttpsBinding(BasicHttpsSecurityMode.Transport)

将其转换为:

listenerBinding: binding

绑定(Binding)被定义为:

var binding = new BasicHttpsBinding(BasicHttpsSecurityMode.Transport)
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;

更多信息请点击此处

并使用您的SSL证书配置服务主机:

listener.ServiceHost.Credentials.ServiceCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindByThumbprint, "Certificate Thumbprint Here");

7
我假设你已经在证书指纹处使用了 X 表示,并将服务器名称更改为“serverurl”,接下来我会使用客户端终结点中看到的值,向你展示服务终结点配置似乎缺失哪些内容。
在设置服务基地址时有两个选项。第一个选项适用于一个服务终结点,并且可以通过简单的配置来解决;只需将地址添加到服务中即可。如下所示:
  <service name="MyApp.ProductServiceManufacturer" behaviorConfiguration="ManufacturerBehaviour">
    <endpoint address="https://serverurl:8088/IServiceInterface/Service.svc" name="ManufacturerProductService" binding="customBinding" bindingConfiguration="HubBinding" contract="MyApp.IProductServiceV20161"/>
  </service>

第二种选项适用于多个主机头或多个服务,希望使用配置转换进行环境部署。此解决方案需要您单独添加基本地址,然后仅在端点地址中引用 *.svc。像这样:
  <service name="MyApp.ProductServiceManufacturer" behaviorConfiguration="ManufacturerBehaviour">
    <endpoint address="Service.svc" name="ManufacturerProductService" binding="customBinding" bindingConfiguration="HubBinding" contract="MyApp.IProductServiceV20161"/>
    <host>
      <baseAddresses>
        <add baseAddress="https://serverurl:8088/IServiceInterface" />
      </baseAddresses>
    </host>
  </service>

尝试其中之一,愉快的编码。
-TwistedStem

你的假设是正确的,我会尝试并更新结果给你,非常感谢。 - Kira
现在我收到了这个错误: 在 _nodetype1_2 上打开期间,副本发生了多次故障。API 调用:IStatelessServiceInstance.Open(); 错误 = System.InvalidOperationException (-2146233079) 该服务包含多个 ServiceEndpoint,其 ContractDescriptions 不同,每个 ContractDescriptions 的 Name ='IProductServiceV20161' 和 Namespace ='http://namespaceurl/'. 提供具有唯一名称和命名空间的 ContractDescriptions,或确保 ServiceEndpoints 具有相同的 ContractDescription 实例。 - Kira
我尝试从app.config文件中删除端点条目,我成功访问了wsdl,但似乎app.config的所有配置(证书)都没有被考虑进去。 - Kira

0

对于那些正在从事类似工作的人,这是我最终得出的结果(并且完美地运行):

protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
        {
            var serviceInstanceListers = new List<ServiceInstanceListener>()
            {
                new ServiceInstanceListener(context =>
                {
                    //return CreateRestListener(context);
                    return CreateSoapHTTPSListener(context);
                }),
            };
            return serviceInstanceListers;
        }

        private static ICommunicationListener CreateSoapHTTPSListener(StatelessServiceContext context)
        {
            var binding = new CustomBinding();
            AsymmetricSecurityBindingElement assbe = (AsymmetricSecurityBindingElement)SecurityBindingElement.CreateMutualCertificateBindingElement(
                           MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10);

            binding.Elements.Add(assbe);
            binding.Elements.Add(new TextMessageEncodingBindingElement());
            binding.Elements.Add(new HttpsTransportBindingElement());
            // Extract the STS certificate from the certificate store.
            X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadOnly);
            X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindByThumbprint, ConfigurationManager.AppSettings.Get("ClientCertificateThumbprint"), false);
            store.Close();
            var identity = EndpointIdentity.CreateX509CertificateIdentity(certs[0]);
            string uri = ConfigurationManager.AppSettings.Get("ServiceUri");

            var listener = new WcfCommunicationListener<IService>(
                serviceContext: context,
                wcfServiceObject: new Service(),//where service implements IService
                listenerBinding: binding,
                address: new EndpointAddress(new Uri(uri), identity)
            );

            listener.ServiceHost.Credentials.ClientCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindByThumbprint, ConfigurationManager.AppSettings.Get("ServiceCertificateThumbprint"));
            listener.ServiceHost.Credentials.ServiceCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindByThumbprint, ConfigurationManager.AppSettings.Get("ClientCertificateThumbprint"));

            // Check to see if the service host already has a ServiceMetadataBehavior
            ServiceMetadataBehavior smb = listener.ServiceHost.Description.Behaviors.Find<ServiceMetadataBehavior>();
            // If not, add one
            if (smb == null)
            {
                smb = new ServiceMetadataBehavior();
                smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy12;
                smb.HttpsGetEnabled = true;
                smb.HttpGetEnabled = false;
                smb.HttpsGetUrl = new Uri(uri);
                listener.ServiceHost.Description.Behaviors.Add(smb);
            }
            return listener;
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接