2014-02-18 44 views
2

我遇到了問題,使用我的c#應用程序設置Microsoft Translator SOAP Service,而不依賴於它生成的app.config文件。沒有配置文件的WCF /服務參考

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,所以我不知道從哪裏開始...

回答

8

有幾個問題先。 當我閱讀它時,您正嘗試使用服務。 這項服務暴露了其WDSL。 現在你是否試圖在不使用由SVCUtil(例如)/ VisualStudioAddServiceReference生成的代理類的情況下使用它?或者你只是想在代碼中配置你的綁定,而不是在app.config中?

如果您試圖在不生成上面指定的代理類的情況下使用該服務,那麼您需要使用動態代理生成工作。 ()。

否則,如果您有生成的代理類,那麼您實際上應該使用app.config來配置綁定,因爲它更容易。 (例如,考慮在您投入生產時端點地址更改) 如果您確實不想使用app.config綁定。然後,按照您現在這樣做的方式,我懷疑您忘記了將要使用的合同添加到綁定中。

見服務的ABC:()

Address 
Binding 
Contract 

您已經有了前兩者,我沒有看到最後一個。

編輯

深入尋找到你的問題更後。還注意到這是一個公共服務器。 我能夠創建綁定以及與服務進行通信。 (除非我得到一個非授權的例外,這是正常的,因爲作爲我沒有令牌

要連接到服務: 在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")); 

第4步:。用客戶端調用一個方法 在你將不得不方法。添加你的「AppId」當您註冊該服務時即告知。 通常從這一點你不應該再遇到任何問題。

讓我知道你是否會遇到它們。

+0

感謝您的回覆。原因是因爲我不想用這個單獨的配置文件運送我的應用程序;在發佈之後,我預計終端地址不會改變。 我到底該如何定義合同?我嘗試添加'binding.Contract = ...',但它給'Contract'引發了一個錯誤'定義'並且沒有擴展方法'Contract' – Spencer

1

我能夠得到它的工作......我正在調用SOAP實例兩次,從而覆蓋對象。

+1

只是剛纔看到你的答案。 我很高興你得到它的工作。 – woutervs