c# - 没有配置文件的 WCF/服务引用

标签 c# wcf

我在设置 Microsoft Translator SOAP Service 时遇到问题使用我的 C# 应用程序,而不依赖于其生成的 app.config 文件。

app.config 文件包含以下内容:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <startup> 

    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/></startup>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_LanguageService" />
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://api.microsofttranslator.com/V2/soap.svc"
                binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_LanguageService"
                contract="Soap.LanguageService" name="BasicHttpBinding_LanguageService" />
        </client>
    </system.serviceModel>
</configuration>

引用这个Stack answer ,我使用了以下方法:

internal static Soap.LanguageServiceClient CreateWebServiceInstance()
{
    BasicHttpBinding binding = new BasicHttpBinding();
    binding.Name = "BasicHttpBinding_LanguageService";
    binding.TextEncoding = System.Text.Encoding.UTF8;
    return new Soap.LanguageServiceClient(binding, new EndpointAddress("http://api.microsofttranslator.com/V2/soap.svc"));
}

但是,即使我在执行翻译服务之前调用了 CreateWebServiceInstance(),我还是得到了这个未处理的异常:

Could not find default endpoint element that references contract 'Soap.LanguageService' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.

我不熟悉 BasicHttpBinding,所以我不确定从哪里开始......

最佳答案

先问几个问题。 当我阅读它时,您正在尝试使用服务。 该服务暴露了它的 WDSL。 现在您是否尝试在不使用 SVCUtil(例如)/VisualStudioAddServiceReference 生成的代理类的情况下使用它?或者您只是想在代码中而不是在 app.config 中配置您的绑定(bind)?

如果您尝试使用服务而不生成上述指定的代理类,那么您需要使用动态代理生成。 ().

否则,如果您生成了代理类,那么您实际上应该使用 app.config 来配置绑定(bind),因为它更方便。 (例如,考虑在您投入生产时端点地址发生变化。) 如果您真的不想使用 app.config 绑定(bind)。然后按照你现在做的方式,我怀疑你忘记了将你想要使用的契约(Contract)添加到你的绑定(bind)中。

查看服务的ABC:()

Address
Binding
Contract

你已经有了前两个,我没有看到最后一个。

编辑

在更深入地研究您的问题之后。并且还注意到这是一个公共(public)服务器。 我能够创建绑定(bind)并与服务通信。 (除非我得到一个未经授权的异常,这是正常的,因为我没有 token 。

要连接到服务: 在 visual studio 中添加对服务的服务引用。 Adding the reference

其次删除上面生成的 app.config 文件。 第三步在某处添加以下代码。

        var binding = new BasicHttpBinding();
        var client = new LanguageServiceClient(binding, new EndpointAddress("http://api.microsofttranslator.com/V2/soap.svc"));

第四步:使用客户端调用方法。 在该方法中,您必须添加注册服务时收到的“AppId”。 通常从这一点开始,您应该不会再遇到任何问题。

如果您无论如何都会遇到它们,请告诉我。

关于c# - 没有配置文件的 WCF/服务引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21856423/

相关文章:

c# - 跟踪工作簿和工作表重命名

c# - 使用位移除以 2 的幂

c# - WCF服务如何检测客户端断开连接

wcf 使用扁平化 WSDL 从 WCF 服务中提取 wsdl

c# - 如何使用 C# 获取 Windows 资源管理器中当前打开的所有文件夹的完整路径?

c# - Windows 事件日志中的 LdapConnection.SendRequest() 问题

c# - Windows窗体应用中的三层架构实现

wcf - 为什么 WCF 中的 DataMember 不能返回类型?

c# - .NET 客户端在调用 Webservice 时不理解 SOAP header

c# - 是否可以使用 C# WCF WebHttpBinding 创建 session (如 php session )?