2016-08-22 82 views
0

我需要構建包括xmlns:u命名空間的以下收據XML結構並將其添加到SOAP標頭。所以年底傳出SOAP頭應該是這個樣子:在WCF中使用命名空間創建自定義MessageHeader

<Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" 
       xmlns:a="http://schemas.xmlsoap.org/ws/2004/08/addressing"> 
    <s:Header> 
     <u:Receipts xmlns:u="http://MyCompany/abc"> 
     <Receipt> 
     <Id /> 
     <Text /> 
     </Receipt> 
     <Receipt> 
     <Id /> 
     <Text /> 
     </Receipt> 
     <Receipt> 
     <Id /> 
     <Text /> 
     </Receipt> 
    </u:Receipts> 
    </s:Header> 
    <s:Body /> 
</Envelope> 

我重寫的MessageHeader類,並建立OnWriteHeaderContents方法的XML。但是,我無法獲得正確的xml /名稱空間。代碼示例表示讚賞!

+0

你可以發佈您的代碼?無論如何,要更改命名空間,您需要創建一個新的Message對象。你是否在合同中設置了名稱空間? –

回答

0

這是我們目前的解決方案,工作正常。

public class ReceiptsHeader : MessageHeader 
{ 
    private const string HeaderName = "Receipts"; 
    private const string HeaderNamespace = "http://MyCompany/abc"; 

    public override string Name => HeaderName; 

    public override string Namespace => HeaderNamespace; 

    private readonly XmlDocument _usageReceipt = new XmlDocument(); 

    public ReceiptsHeader(IEnumerable elements) 
    { 
     var headerString = new StringBuilder("<Receipts xmlns=\"http://MyCompany/abc\">"); 
     foreach (var elem in elements) 
     { 
      // Build <Receipt> nodes here... 
     } 
     headerString.Append("</Receipts>"); 

     _usageReceipt.LoadXml(headerString.ToString()); 
    } 

    protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion) 
    { 
     foreach (XmlNode node in _usageReceipt.ChildNodes[0].ChildNodes) 
      writer.WriteNode(node.CreateNavigator(), false); 

    } 
} 

我們再在BeforeSendReply方法添加這SOAP頭,這樣的事情:

ReceiptsHeader head = new ReceiptsHeader(elements); 
reply.Headers.Add(head);