2015-02-23 147 views
2

所以我試圖對使用HTTP身份驗證的web服務進行SOAP調用。我在Visual Studio中添加了一個Web引用,它爲我生成了一個包裝類。以下是我如何撥打電話的示例代碼:C#:如何在進行SOAP調用時使用HTTP身份驗證?

var prox = new WebserviceNamespace.WebService(); 
prox.Credentials = new NetworkCredential("username", "password"); 
prox.PreAuthenticate = true; 
var resp = prox.webMethod(null, null); 

最後一行將引發「驗證失敗」消息。

我使用wireshark來檢查它是否試圖向HTTP數據包添加基本身份驗證,並且看起來不像它。這裏是Wireshark輸出:

POST /cms/services/WebService HTTP/1.1\r\n 
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 4.0.30319.34209)\r\n 
VsDebuggerCausalityData: uIDPo7e/OYIGV2VDs7nYMO5QmegAAAAAWxFxk5NzcUSF5zGIxQ1REwb488ITippOiEKaDSmuFDkACQAA\r\n 
Content-Type: text/xml; charset=utf-8\r\n 
SOAPAction: ""\r\n 
Host: sub.domain.com\r\n 
Content-Length: 343\r\n 
Expect: 100-continue\r\n 
Connection: Keep-Alive\r\n 
\r\n 
[Full request URI: http://sub.domain.com/cms/services/WebService3.0] 
[HTTP request 2/2] 
[Response in frame: 265321]eXtensible Markup Language 
<?xml 
<soap:Envelope 
    xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <soap:Body> 
     <webMethod 
      xmlns="WebService"> 
      <in0 xsi:nil="true"/> 
      <in1 
       xsi:nil="true"/> 
      </webMethod> 
     </soap:Body> 
    </soap:Envelope> 

我期待看到HTTP認證這樣一行:

Authorization: Basic SUNOOnNwc3pK 

會有人碰巧知道我在做什麼錯在這裏?

回答

3

終於明白了這一點。這個非常小的文章對我來說是關鍵的:http://blog.kowalczyk.info/article/at3/Forcing-basic-http-authentication-for-HttpWebReq.html

基本上只有在服務器挑戰你的請求時才使用憑證屬性。如果服務器不挑戰它可能會失敗(就像我發生的那樣)。我所要做的就是編輯自動生成的代理類,將此代碼添加到它(通過上面的鏈接啓發):

protected override WebRequest GetWebRequest(Uri uri) 
    { 
     HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(uri); 
     String authInfo = Convert.ToBase64String(Encoding.Default.GetBytes("username:password")); 
     request.Headers["Authorization"] = "Basic " + authInfo; 
     return request; 
    } 

隨着到位,我不再得到驗證錯誤!

+0

你小裂口!非常感謝您發佈此內容,經過數小時試圖讓我的請求工作,添加幾行代碼(並輸入我自己的用戶名和密碼,當然)使這一切工作!謝謝,謝謝! :-) – Tony 2015-03-27 02:56:16