带服务结构的SOAP - Https和Http绑定

时间:2018-03-27 12:12:43

标签: c# wcf azure-service-fabric

我目前正在开发一个服务结构应用程序,它将公开将由另一个应用程序使用的soap监听器

我不断收到错误

  

无法找到与方案https匹配的基地址   具有绑定CustomBinding的端点。注册的基地址方案   是[]

这里是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's answer我在这里更新了我的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;
    }

然后我得到一个错误说:

  

服务包含多个具有不同ContractDescriptions的ServiceEndpoints,每个ServiceDescription都具有Name ='IProductServiceV20161'和Namespace ='namespaceurl /'

我想这是因为app.config文件中有两个服务端点定义,而.cs文件中有另一个定义 我评论了app.config中的端点标记并且它有效。 但是,与我使用WCF应用程序获得的文件相比,我得到的wsdl文件缺少一些条目。

更新2: 如何为服务指定端点标识?是否可以使用自定义BindingElementExtensionElement类?

3 个答案:

答案 0 :(得分:8)

确保服务清单中的端点被声明为类型&#39; HTTPS&#39;并将SSL证书添加到WCF服务主机。

你能尝试改变这个:

listenerBinding: new BasicHttpsBinding(BasicHttpsSecurityMode.Transport)

进入这个:

listenerBinding: binding

其中绑定定义为:

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

更多信息here

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

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

答案 1 :(得分: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

答案 2 :(得分: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;
        }