我正在使用Visual Studio 2010中的WCF編寫針對供應商的webservice的客戶端。我無法更改其實現或配置。通過WCF調用第三方安全web服務 - 身份驗證問題
針對他們的測試服務器上的安裝運行,我沒有問題。我從他們的WSDL添加一個服務引用,在代碼中設置的網址,併發出的呼籲:
var client = new TheirWebservicePortTypeClient();
client.Endpoint.Address = new System.ServiceModel.EndpointAddress(webServiceUrl);
if (webServiceUsername != "")
{
client.ClientCredentials.UserName.UserName = webServiceUsername;
client.ClientCredentials.UserName.Password = webServicePassword;
}
TheirWebserviceResponse response = client.TheirOperation(myRequest);
簡單明瞭。直到他們將其移至生產服務器並將其配置爲使用https。然後我得到這個錯誤:
The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'Basic realm='.
所以我去尋求幫助。我發現這個:Can not call web service with basic authentication using wcf。
批准的回答表明這一點:
BasicHttpBinding binding = new BasicHttpBinding();
binding.SendTimeout = TimeSpan.FromSeconds(25);
binding.Security.Mode = BasicHttpSecurityMode.Transport;
binding.Security.Transport.ClientCredentialType =
HttpClientCredentialType.Basic;
EndpointAddress address = new EndpointAddress(your-url-here);
ChannelFactory<MyService> factory =
new ChannelFactory<MyService>(binding, address);
MyService proxy = factory.CreateChannel();
proxy.ClientCredentials.UserName.UserName = "username";
proxy.ClientCredentials.UserName.Password = "password";
這似乎也很簡單。除了我試圖找出從wsdl生成的多個類和接口中的哪一個來創建服務引用之外,我應該使用它來代替上面的「MyService」。
我的第一次嘗試是使用「TheirWebservicePortTypeClient」 - 我在前一個版本中實例化的類。這給了我一個運行時錯誤:
The type argument passed to the generic ChannelFactory class must be an interface type.
因此,我深入生成的代碼,多一點。我看到這一點:
public partial class TheirWebservicePortTypeClient
:
System.ServiceModel.ClientBase<TheirWebservicePortType>,
TheirWebservicePortType
{
...
}
所以,我想實例的ChannelFactory <>與TheirWebservicePortType。
這給了我編譯時的錯誤。生成的代理沒有ClientCredentials成員或ItsOperation()方法。
所以我嘗試了「System.ServiceModel.ClientBase」。
實例化ChannelFactory> <>它仍然給我編譯時錯誤。產生的代理確實有一個ClientCredentials成員,但它仍然沒有一個TheirOperation()方法。
那麼,什麼給了?如何從WCF客戶端將用戶名/密碼傳遞給HTTPS Web服務?
====================編輯說明解決方案====================
首先,建議使用TheirWebservicePortType實例化工廠,將用戶名和密碼添加到factory.Credentials中,而不是proxy.ClientCredentials正常工作。除了一點混淆。
也許這與wsdl寫入的奇怪方式有關,但客戶端類YourWebservicePortTypeClient將TheirOperation定義爲接受Request參數並返回Response結果。 TheirWebservicePortType接口將TheirOperation定義爲接受一個TheirOperation_Input參數,並返回一個TheirOperation_Output結果,其中TheirOperation_Input包含一個Request成員,而TheirOperation_Output包含一個Response成員。
在任何情況下,如果我從通過請求構建的TheirOperation_Input對象,調用代理成功,然後我可以提取返回TheirOperation_Output對象所含的響應對象:
TheirOperation_Output output = client.TheirOperation(new TheirOperation_Input(request));
TheirWebserviceResponse response = output.TheirWebserviceResponse;
我使用哪個類或接口來實例化ChannelFactory <>,以便生成的代理工作? – 2012-08-03 13:12:28
從你所描述的你使用'TheirWebservicePortType' – 2012-08-03 15:43:54