WCF序列化UnitTests和此XmlWriter不支持base64编码数据.我应该用什么作家?

Amy*_*y B 5 wcf serialization unit-testing binary-data

我正在编写一些单元测试,用于序列化和反序列化可能跨越WCF边界的所有类型,以证明所有属性都将转移到另一侧.

我用byte []属性遇到了一些麻烦.

[DataContract(IsReference=true)]
public class BinaryDataObject
{
    [DataMember]
    public byte[] Data { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

当我通过测试运行此对象时,我得到System.NotSupportedException : This XmlWriter does not support base64 encoded data.

这是我的序列化方法:

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;
}
Run Code Online (Sandbox Code Playgroud)

我发现我的序列化方法必须有缺陷--WCF可能不使用XDocument实例,也可能不使用System.Xml.XmlWriter实例.

WCF默认使用什么Writer?我想在我的测试中使用那种类型的实例.

Jes*_*cer 5

使用我的Reflector忍者技能,似乎它使用了一些内部类型:XmlDictionaryWriter的子类.Serialize像这样重写你的方法:

    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;
    }
Run Code Online (Sandbox Code Playgroud)

所有人都应该修补.