【问题标题】:Connect WCF client without config file (but via code)?连接没有配置文件的 WCF 客户端(但通过代码)?
【发布时间】:2017-12-12 14:00:29
【问题描述】:

我知道这个问题已经被问过(以某种形式),但我是新手,无法让它发挥作用。 问题:需要创建一个我需要从 PowerBuilder(通过 COM)调用的 .NET dll (c#) --> dll 将处理 SOAP 客户端对 Web 服务的调用。

在 .NET 方面没有太多经验,但设法与(例如)公共 Web 服务“对话”。但问题是我不能使用配置文件(否则找不到端点的错误)。

请问,谁能帮我解决这个问题(可能是示例代码)?

这是配置文件:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="GlobalWeatherSoap" />
      </basicHttpBinding>
      <customBinding>
        <binding name="GlobalWeatherSoap12">
          <textMessageEncoding messageVersion="Soap12" />
          <httpTransport />
        </binding>
      </customBinding>
    </bindings>
    <client>
      <endpoint address="http://www.webservicex.com/globalweather.asmx"
          binding="basicHttpBinding" bindingConfiguration="GlobalWeatherSoap"
          contract="SrvRefWeather.GlobalWeatherSoap" name="GlobalWeatherSoap" />
      <endpoint address="http://www.webservicex.com/globalweather.asmx"
          binding="customBinding" bindingConfiguration="GlobalWeatherSoap12"
          contract="SrvRefWeather.GlobalWeatherSoap" name="GlobalWeatherSoap12" />
    </client>
  </system.serviceModel>
</configuration>

我通过 WSDL 文件添加了一个“服务引用”并像这样调用 web 服务(例如):

SrvRefWeather.GlobalWeatherSoapClient client = new SrvRefWeather.GlobalWeatherSoapClient("GlobalWeatherSoap");
string strCities = client.GetCitiesByCountry("Belgium");

谁能告诉我如何在没有配置文件的情况下实现与我所做的相同的操作?

我认为我需要通过“BasicHttpBinding()”,但在我的示例中不知道如何引用“SrvRefWeather”对象。

任何帮助将不胜感激!真的……

谢谢, 马克。

【问题讨论】:

    标签: c# web-services wcf soap basichttpbinding


    【解决方案1】:

    我设法使这个(简单的)示例工作:

    BasicHttpBinding binding = new BasicHttpBinding();
    EndpointAddress address = new EndpointAddress("http://www.webservicex.com/globalweather.asmx");
    
    SrvRefWeather.GlobalWeatherSoapClient client = new SrvRefWeather.GlobalWeatherSoapClient(binding, address);
    string strCities = client.GetCitiesByCountry("Belgium");
    

    谁能向我解释一下“配置文件中的合同标签”的含义? example here

    我在这里的示例中没有使用它,但它可以工作...... 所以我想知道它在哪里(以及是否)使用?

    谢谢。

    【讨论】:

    • 你肯定需要合约:要连接到你需要的服务 ABC = 地址、绑定、合约。可能您的代理 GlobalWeatherSoapClient 有一个 ServiceContractAttribute 来定义合约(ConfigurationName 属性,或默认为类型名称)。
    • 嗨@Joe,感谢您的回复(和信息)。我会(尝试)进一步调查您的答案。
    【解决方案2】:

    不回答您的问题,但我个人始终会使用 XML 配置,因为它比在代码中创建所有内容更容易阅读和理解。

    如果您不想要/不能有外部配置文件,您可以将配置 XML 包含在您的程序集中,例如作为字符串常量或嵌入资源。然后,您可以使用 ConfigurationChannelFactory 类从该配置数据创建您的客户端通道。

    如果您想探索这种方法但不了解如何使用 ConfigurationChannelFactory 来实现此目的,请发表评论或提出其他问题。

    【讨论】:

    • 谢谢乔。我不介意有一个外部配置文件,但我不能有一个外部配置文件(它是 PowerBuilder,它将通过 COM 调用这个 dll,它是调用 exe,它应该有一个在这里不起作用的 CONFIG 文件)。
    • 我一定会研究有关嵌入式资源的解决方案。看起来很有趣!
    猜你喜欢
    • 2014-02-23
    • 1970-01-01
    • 1970-01-01
    • 2015-05-22
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 2018-04-23
    相关资源
    最近更新 更多