[英]WCF -Rest- DataContract : Deserialize XML wrapped response
Assuming we are using a REST WCF service returning xml. 假设我们正在使用返回XML的REST WCF服务。
Is it possible to deserialize "automatically" an xml wrapped response to a DataContract ? 是否可以“自动”反序列化对DataContract的xml包装的响应?
Simple example 简单的例子
Class: 类:
[DataContract]
public class TestClass
{
[DataMember]
string StringValue { get; set; }
[DataMember]
int IntValue { get; set; }
}
Service: 服务:
[OperationContract]
[WebGet(UriTemplate = "Test",
BodyStyle = WebMessageBodyStyle.Wrapped,
RequestFormat = WebMessageFormat.Xml,
ResponseFormat = WebMessageFormat.Xml)]
TestClass Test();
Client: 客户:
using (WebClient webClient = new WebClient())
{
webClient.Headers["Content-type"] = "application/xml";
webClient.Encoding = Encoding.UTF8;
return webClient.DownloadString($"{BASE_URL}/Test");
}
Deserialization: 反序列化:
// With T as TestClass in or example.
public static T Deserialize<T>(string xml)
{
using (Stream stream = new MemoryStream())
{
byte[] data = System.Text.Encoding.UTF8.GetBytes(xml);
stream.Write(data, 0, data.Length);
stream.Position = 0;
DataContractSerializer deserializer =
new DataContractSerializer(typeof(T));
return (T)deserializer.ReadObject(stream);
}
}
This code works well for bare response. 此代码可以很好地响应裸露的情况。
As webClient just return the full request, output xml contains thre wrapper element, and DataContractSerializer try parse a simple string, and don't now it come from WCF wrapped response (and should "forget" the wrapper). 由于webClient只是返回完整的请求,因此输出xml中包含包装器元素,DataContractSerializer尝试解析一个简单的字符串,现在不要来自WCF包装的响应(应该“忘记”包装器)。
Goal is to construct a client where wrapping style (bare/wrapped) doesn't matter. 目标是在包装样式(裸/包裹)无关紧要的情况下构建客户。
why don't you just deserialize the output as a simple XML? 为什么不将输出反序列化为简单的XML? something like this: 像这样的东西:
public static T XmlDeserializer<T>(string xmlString)
{
var instance = default(T);
var xmlSerializer = new XmlSerializer(typeof(T));
using (var stringreader = new StringReader(xmlString))
instance = (T)xmlSerializer.Deserialize(stringreader);
return instance;
}
note: because of default xmlns
tags you should use name space in your client side class like this: 注意:由于有默认的xmlns
标记,因此应在客户端类中使用名称空间,如下所示:
[DataContract(Namespace = "http://schemas.datacontract.org/2004/07/WcfWebService")]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.