通过Http和Https使用WCF调用Web服务

Lew*_*wis 12 asp.net https wcf http

在我们的项目中,我们有一个运行在http和https上的java Web服务.我们希望内部使用http,并使用https作为我们的Web应用程序的外部版本.

所以我们在我们的应用程序中创建了代理类,我们在web/app.config中设置了http的绑定,一切正常.

在外部应用程序中,我们需要对代码和配置进行哪些更改以支持相同服务的https?如果可能请提供代码片段来解释!

jef*_*ebe 22

我找到了一个围绕MSDN的答案.

就我而言,我使用的是自定义绑定:

<customBinding>
    <binding name="jsonpBinding">
        <jsonpMessageEncoding/>
        <httpTransport manualAddressing="true"/>
    </binding>
</customBinding>
Run Code Online (Sandbox Code Playgroud)

这是在服务中引用的

<services>
    <service name="{YourInfoHere}">
        <endpoint address="" binding="customBinding" bindingConfiguration="jsonpBinding" behaviorConfiguration="{YourInfoHere}" contract="{YourInfoHere}"/>
    </service>
</services>
Run Code Online (Sandbox Code Playgroud)

添加使用httpsTransport的第二个绑定,然后添加使用该绑定的第二个服务.最终输出:

    <services>
        <service name="{YourInfoHere}">
            <endpoint address="" binding="customBinding" bindingConfiguration="jsonpBinding" behaviorConfiguration="{YourInfoHere}" contract="{YourInfoHere}"/>
            <endpoint address="" binding="customBinding" bindingConfiguration="jsonpBindingHttps" behaviorConfiguration="{YourInfoHere}" contract="{YourInfoHere}"/>
        </service>
    </services>
    <bindings>
        <customBinding>
            <binding name="jsonpBinding">
                <jsonpMessageEncoding/>
                <httpTransport manualAddressing="true"/>
            </binding>
            <binding name="jsonpBindingHttps">
                <jsonpMessageEncoding/>
                <httpsTransport manualAddressing="true" />
            </binding>
        </customBinding>
    </bindings>
Run Code Online (Sandbox Code Playgroud)

可能不太理想,但它确实有效.这些是我为使SSL工作所做的唯一更改.由于它全部在绑定和传输中,因此代码保持不变.

相关的MSDN链接:

  1. 自定义绑定:http://msdn.microsoft.com/en-us/library/ms731377.aspx
  2. HttpTransport:http://msdn.microsoft.com/en-us/library/system.servicemodel.channels.httptransportbindingelement.aspx
  3. HttpsTransport:http://msdn.microsoft.com/en-us/library/system.servicemodel.channels.httpstransportbindingelement.aspx


And*_*are 0

请参阅配置 HTTP 和 HTTPS

通过 HTTP 使用 Windows Communication Foundation (WCF) 需要使用主机,例如 Internet 信息服务 (IIS),或者通过 HTTP 服务器 API 手动配置 HTTP 设置。本文档介绍使用 HTTP 和 HTTPS 时手动配置 WCF。

另请参阅HTTPS 所需的 WCF 绑定

我刚刚编写完第一个生产 WCF 应用程序,该应用程序运行良好,直到我将其部署到生产环境中。突然之间,所有 WCF 调用都不起作用,并且我会收到 JavaScript“TestService 未定义”错误。当我查看 JS 服务引用(在调试模式下)时,出现以下错误:

找不到与绑定 WebHttpBinding 的端点的方案 http 匹配的基地址。注册的基地址方案是[https]

显然,我的 WCF 服务将自身注册为 HTTPS(因为它是通过 SSL 实现的),但我的绑定仅配置为 HTTP。解决方案是在 Web.Config 文件中定义自定义绑定,并将安全模式设置为“传输”。然后,您只需在端点定义中使用 bindingConfiguration 属性来指向您的自定义绑定。整个支持 HTTPS 的 system.serviceModel 部分如下: