2010-06-30 78 views
0

您好我有一個服務代理的一個方法:XmlElement的包裹在額外的標籤在SOAP請求

void SendRequest(MyMessage msg); 

的MyMessage定義如下:

[MessageContract(IsWrapped=false)] 
public class MyMessage{ 
    [MessageBodyMember(Order=0)] 
    public XmlElement Body; 

    public MyMessage(XmlElement Body){ 
     this.Body = Body; 
    } 
} 

現在的問題是,當我發送請求,身體包裹在一個標籤,像這樣:

<s:Body> 
    <Body> 
     <MyMessage> 
       <SomeData>Hello world</SomeData> 
     </MyMessage> 
    </Body> 
</s:Body> 

當我真正想要的是:

<s:Body> 
    <MyMessage> 
       <SomeData>Hello world</SomeData> 
    </MyMessage> 
</s:Body> 

有人可以幫忙嗎?我開始變得絕望了! :/

編輯:我想發送XmlElement的原因是該服務將接受各種數量的XML格式,並將在服務器端進行xsd驗證和轉換。這只是一種包裝。

我也沒辦法讓端點服務器只接受「錯誤的」xml結構,因爲我不能控制它。

回答

2

好的,所以看來我不得不完全不習慣WCF這個工作。

我所做的是創建兩個簡單的方法:

XDocument ConstructSoapEnvelope(string messageId, string action, XDocument body) 
    { 
     XDocument xd = new XDocument(); 
     XNamespace s = "http://schemas.xmlsoap.org/soap/envelope/"; 
     XNamespace a = "http://www.w3.org/2005/08/addressing"; 

     XElement soapEnvelope = new XElement(s + "Envelope", new XAttribute(XNamespace.Xmlns + "s", s), new XAttribute(XNamespace.Xmlns + "a", a)); 
     XElement header = new XElement(s + "Header"); 
     XElement xmsgId = new XElement(a + "MessageID", "uuid:" + messageId); 
     XElement xaction = new XElement(a + "Action", action); 
     header.Add(xmsgId); 
     header.Add(xaction); 

     XElement soapBody = new XElement(s + "Body", body.Root); 
     soapEnvelope.Add(header); 
     soapEnvelope.Add(soapBody); 
     xd = new XDocument(soapEnvelope); 
     return xd; 
    } 

    string HttpSOAPRequest(XmlDocument doc, string add, string proxy, X509Certificate2Collection certs) 
    { 
     HttpWebRequest req = (HttpWebRequest)WebRequest.Create(add); 
     req.ClientCertificates = certs; 
     if (proxy != null) req.Proxy = new WebProxy("", true); 

     req.Headers.Add("SOAPAction", "\"\""); 

     req.ContentType = "text/xml;charset=\"utf-8\""; 
     req.Accept = "text/xml"; 
     req.Method = "POST"; 
     Stream stm = req.GetRequestStream(); 
     doc.Save(stm); 
     stm.Close(); 
     WebResponse resp = req.GetResponse(); 
     stm = resp.GetResponseStream(); 
     StreamReader r = new StreamReader(stm); 

     return r.ReadToEnd(); 
    } 

ConstructSoapEnvelope只需創建一個SOAP信封用頭和主體(專爲我需要用的WS-Addressing)

和HttpSOAPRequest是一個略加修改的版本在這裏找到: http://www.eggheadcafe.com/articles/20011103.asp

我不得不修改它接受客戶證書,爲了我的SSL通信的工作..

希望這可以幫助別人! :)