2013-09-24 34 views
8

我想在調用Web服務之前在C#中添加自定義SOAP頭信息。我正在使用SOAP Header類來完成此操作。我可以做到這一點,但不完全是我需要的方式。這裏是我所需要的肥皂頭看起來像在C#中爲Web服務調用添加自定義SOAPHeader

<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:Header> 
     <Security xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"> 
     <UsernameToken> 
     <Username>USERID</Username> 
     <Password>PASSWORD</Password> 
     </UsernameToken>  
     </Security> 
    </soap:Header> 
    <soap:Body> 
    ... 

我能夠添加SOAP頭,如下

<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:Header> 
     <UsernameToken xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"> 
     <Username>UserID</Username> 
     <Password>Test</Password> 
     </UsernameToken> 
    </soap:Header> 
    <soap:Body> 

我什麼不能夠做的就是添加它包裝的「安全性」元素如第一個示例中的「UsernameToken」。任何幫助,將不勝感激。

回答

1

此鏈接adding soap header爲我工作。我正在調用一個我沒寫並且無法控制的SOAP 1.1服務。我使用VS 2012並在我的項目中添加了該服務作爲Web引用。希望這會有所幫助

我按照J. Dudgeon的帖子向線程底部的步驟1-5操作。

下面是一些示例代碼(這將是在一個單獨的cs文件):

namespace SAME_NAMESPACE_AS_PROXY_CLASS 
{ 
    // This is needed since the web service must have the username and pwd passed in a custom SOAP header, apparently 
    public partial class MyService : System.Web.Services.Protocols.SoapHttpClientProtocol 
    { 
     public Creds credHeader; // will hold the creds that are passed in the SOAP Header 
    } 

    [XmlRoot(Namespace = "http://cnn.com/xy")] // your service's namespace goes in quotes 
    public class Creds : SoapHeader 
    { 
     public string Username; 
     public string Password; 
    } 
} 

然後在生成的代理類,上調用服務的方法中,各項J達吉恩的步驟4添加此屬性:[SoapHeader("credHeader", Direction = SoapHeaderDirection.In)]

最後,這裏的調用生成的代理方法,用頭:

using (MyService client = new MyService()) 
{ 
    client.credHeader = new Creds(); 
    client.credHeader.Username = "username"; 
    client.credHeader.Password = "pwd"; 
    rResponse = client.MyProxyMethodHere(); 
} 
+0

提供的示例代碼的任何機會呢?提前致謝。 (我正在查看鏈接/步驟,並試圖使他的問題與他/ Dudgeon的示例代碼一致,但不直接對應/點擊我如何翻譯安全頭部要求)。 – Terry

+1

參見上面我添加了一些示例代碼。順便說一句,希望這有助於 –

+0

- 這不是一個WCF服務,可能對某些人來說很明顯 –