WCF Serialization UnitTests and This XmlWriter does not support base64 encoded data. What Writer should I use?
I'm writing some unit tests that serialize and deserialize all of our types that might cross the WCF boundary, in order to prove that all properties will make it to the other side.
I've hit a bit of a snag with a byte[] property.
[DataContract(IsReference=true)]
public class BinaryDataObject
{
[DataMember]
public byte[] Data { get; set; }
}
When I run this object through the testing, I get System.NotSupportedException: This XmlWriter does not support base64 encoded data
.
Here's my Serialization method开发者_JAVA技巧:
public static XDocument Serialize(object source)
{
XDocument target = new XDocument();
using (System.Xml.XmlWriter writer = target.CreateWriter())
{
DataContractSerializer s = new DataContractSerializer(source.GetType());
s.WriteObject(writer, source);
}
return target;
}
It occurs to me that my serialization method must be flawed - WCF probably doesn't use XDocument
instances and might not use System.Xml.XmlWriter
instances.
What Writer does WCF use by default? I'd like to use instances of that type in my test.
Using my Reflector ninja skills, it seems like it uses some internal types: subclasses of XmlDictionaryWriter. Rewrite your Serialize
method as such:
public static XDocument Serialize(object source)
{
XDocument target;
using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
using (System.Xml.XmlWriter writer = XmlDictionaryWriter.CreateTextWriter(stream))
{
DataContractSerializer s = new DataContractSerializer(source.GetType());
s.WriteObject(writer, source);
writer.Flush();
stream.Position = 0;
target = XDocument.Load(stream);
}
return target;
}
and all shall be mended.
精彩评论