我的应用程序中的架构有点像这样
MainUI------->WCF------->BLL------->DAL
我正在使用 Entity Framework 4.0 和 .Net Framework 4.0。
我的数据访问层返回 PoCo 对象,该对象在传入和传出对象时被序列化和反序列化。
现在,当 WCF 在它被序列化之前返回对象时,它很好,正如我所期望的那样,但是当它被反序列化时,它有时会错过我的自定义对象的某些属性(导航属性),并非总是如此,而是有时。特别是当我通过网络发送自定义对象列表时。它始终返回单个对象的值。
作为记录,我正在使用 DataContract Serializer。
我想了解这个序列化/反序列化过程。而且我还想查看序列化对象以及对象序列化和反序列化的确切点。
最佳答案
我不相信有一种简单的方法可以调试序列化,但实际上,没有什么神奇之处:序列化是一个相当简单的过程,您可以自己完成。
For the record, I am using DataContract Serializer.
这是序列化/反序列化的代码
public static string Serialize(object obj) {
using(MemoryStream memoryStream = new MemoryStream())
using(StreamReader reader = new StreamReader(memoryStream)) {
DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
serializer.WriteObject(memoryStream, obj);
memoryStream.Position = 0;
return reader.ReadToEnd();
}
}
public static object Deserialize(string xml, Type toType) {
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(toType);
return deserializer.ReadObject(stream);
}
}
it sometimes misses some properties
基本上,如果在序列化过程中出现问题,序列化程序将抛出 SerializationException(包含详细信息)。在您的情况下(属性仍然为空或等于默认值),听起来您忘记了某些属性。
好吧,在没有任何代码的情况下对您提供更多帮助并不容易,但请注意 datacontractserializer 功能(请参阅 here )。
Especially when i send List of custom objects over the wire. It returns the values for the single object all the time.
尝试重现它并为此编写单元测试。没有随机错误,只有导致错误的非常具体的场景。
关于wcf - .Net 中的序列化内部结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16317731/