2016-09-06 131 views
0

使用Web服務,我想消費使用此代碼Web服務:C#和基本身份驗證

WebService.GenRelClient client = new WebService.GenRelClient(); 
client.ClientCredentials.UserName.UserName = @"UserName"; 
client.ClientCredentials.UserName.Password = @"Password"; 
var response = client.returnString("test"); 

而且我的配置是這樣的:

<?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="GenRelClientPortBinding"> 
     <security mode="TransportCredentialOnly"> 
      <transport clientCredentialType="Basic" /> 
     </security> 
     </binding> 
     </basicHttpBinding> 
    </bindings> 
    <client> 
     <endpoint 
      address="http://ws.domain.com/GenRel/GenRel" 
      binding="basicHttpBinding" 
      bindingConfiguration="GenRelClientPortBinding" 
      contract="WebService.GenRelClientPort" 
      name="GenRelClientPort" /> 
    </client> 
    </system.serviceModel> 
</configuration> 

請求被髮送到Web服務和迴應帶有關於它需要的錯誤消息發回基本身份驗證因爲請求可能沒有憑據發送,所以我不知道錯誤在哪裏。

謝謝您的幫助

+0

我不同意,這個問題是與標題問題的副本「如何用戶憑據傳遞到Web服務」 。 Bushwacka面臨的問題是服務器配置爲使用搶先式身份驗證。一個非常特殊的情況,需要客戶端在SOAP頭中發送認證信息。在前面提到的問題中,這些都沒有涉及。 –

回答

5

爲你能夠調用Web服務,您將需要安全信息添加到SOAP頭。

點擊here閱讀MSDN文章,解釋基本原則。

看看下面的代碼示例,看看它是否解決您的問題:

var client = new WCClient(); 
using (OperationContextScope scope = new OperationContextScope(client.InnerChannel)) 
{ 
    var httpRequestProperty = new HttpRequestMessageProperty(); 
    httpRequestProperty.Headers[System.Net.HttpRequestHeader.Authorization] = "Basic " + 
        Convert.ToBase64String(Encoding.ASCII.GetBytes(client.ClientCredentials.UserName.UserName + ":" + 
        client.ClientCredentials.UserName.Password)); 
    OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty; 

    client.DoSomething(); 
} 
+0

感謝您的回答,但我無法訪問主機,我只能使用該服務。我測試了通過SoapUI工具發送的請求,並且它工作正常,我用帶有用戶名和密碼的請求發送了預先驗證的身份驗證,所以我需要在C#中執行此操作。 – Bushwacka

+0

現在完美,它工作的很好! – Bushwacka