WCF RESTFul service - Pass XML as string to servic

2019-07-26 04:36发布

I need to be able to pass XML to a RESTFul WCF service as a string, however I am struggling to do so. Can someone please let me know how I could do this? It must be sent as a string, I cannot wrap it in a data contract etc. Example of the service contract below

[OperationContract]
[WebInvoke(Method = "POST",
            UriTemplate = "lookup",
            BodyStyle = WebMessageBodyStyle.Bare,
            ResponseFormat = WebMessageFormat.Xml)]
Stream LookupPostcode(string requestXml);

Many thanks in advance

标签: xml wcf rest
4条回答
成全新的幸福
2楼-- · 2019-07-26 05:03

Wrapping the xml in CDATA tags stops the parser from treating it as xml:

myString = "<![CDATA[<thexml/>]]>"
查看更多
ら.Afraid
3楼-- · 2019-07-26 05:15

It's a major hack, but you can wrap your XML inside a <string> tag like this.

 XmlDocument body = new XmlDocument();
 body.Load(...);

 postData = @"<string xmlns='http://schemas.microsoft.com/2003/10/Serialization/'><![CDATA[" + body.OuterXml + "]]></string>";
查看更多
冷血范
4楼-- · 2019-07-26 05:15

Try using XElement or Stream as your method parameter.

[OperationContract] 
[WebInvoke(Method = "POST",
           UriTemplate = "lookup",
           BodyStyle = WebMessageBodyStyle.Bare,
           ResponseFormat = WebMessageFormat.Xml)] 
Stream LookupPostcode(Stream requestXml); 

...

[OperationContract] 
[WebInvoke(Method = "POST",
           UriTemplate = "lookup",
           BodyStyle = WebMessageBodyStyle.Bare,
           ResponseFormat = WebMessageFormat.Xml)] 
Stream LookupPostcode(XElement requestXml); 

... Not sure what you are trying to do inside of the method or I could probably provide more help.

查看更多
混吃等死
5楼-- · 2019-07-26 05:27

This is completely off-topic, but trying to bend WCF to be RESTful will be a constant battle and you will ultimately surrender. It's the message-oriented RPC- and SOAP-based configure-everything-in-XML nature of WCF that makes it so hard to write simple REST services.

If you're not neck-deep in your project, try researching other alternatives and abandon WCF for that purpose.

查看更多
登录 后发表回答