XmlElement包装在SOAP请求中的额外标记中

时间:2010-06-30 08:58:57

标签: c# .net wcf soap c#-4.0

您好我有一个服务代理,有一种方法:

void SendRequest(MyMessage msg);

MyMessage的定义如下:

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

    public MyMessage(XmlElement Body){
        this.Body = 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结构,因为我无法控制它。

1 个答案:

答案 0 :(得分: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-envelope(根据我的需要使用ws-addressing定制)

和HttpSOAPRequest是稍微修改过的版本: http://www.eggheadcafe.com/articles/20011103.asp

我必须修改它才能接受客户端证书,以便我的SSL通信能够正常工作..

希望这对其他人也有帮助! :)