XML format in WCF REST request and response
我已经设置了一个 WCF 服务,它将以相同的方法同时接受 JSON 和 XML,并且支持 SOAP 和 REST。
JSON 工作正常,但我不知道 XML 应该是什么样子。
界面如下:
1
2 3 4 5 6 7 |
[ServiceContract]
public interface IWebService { [OperationContract] [WebInvoke(BodyStyle = WebMessageBodyStyle.Bare)] string[] EchoArray(string[] stringArray); } |
如果可能的话,我希望 XML 尽可能简单,没有命名空间,像这样:
1
2 3 4 |
<stringArray>
<string>hello</string> <string>hola</string> </stringArray> |
响应也应该很简单。
如果有什么不同,我都是在代码中完成的,没有任何 web.config。
这样我就可以使用 Azure 辅助角色了。
我决定使用打包的请求而不是裸请求(因为另一种方法需要它),并想出了如何格式化它。
首先我改变了
1
|
[ServiceContract]
|
到
1
|
[ServiceContract(Namespace =“”)]
|
然后这个工作:
1
2 3 4 5 6 |
<EchoArray>
<stringArray xmlns:a=“http://schemas.microsoft.com/2003/10/Serialization/Arrays”> hello</a:string> hola</a:string> </stringArray> </EchoArray> |
如果没有封装的请求,它可能也可以工作,但是为了保持一致性,我也封装了这个方法。
如果你想控制 XML 的外观,你可以这样做:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
[ServiceContract]
public interface IWebService { [OperationContract] [WebInvoke(BodyStyle = WebMessageBodyStyle.Bare)] StringArray EchoArray(StringArray stringArray); } public class StringArray : IXmlSerializable { public void ReadXml(XmlReader reader) { public void WriteXml(XmlWriter writer) { |
来源:https://www.codenong.com/4957254/