WCF 错误:期望状态 'Element'.. 遇到名称为 ''、命名空间 '' 的 'Text' 以 XML 格式发布调用

问题描述

我有一个 WCF 服务方法,它无法反序列化 XML 格式的帖子,并且会出错

第 14 行位置 30 中的错误。期望状态“元素”..遇到 名称为''的'文本',命名空间为''

我缩小到特定部分,如下面的可重现示例

var xmlSrc = @"<Keys>
                  <ProductKeyID>123</ProductKeyID>
                  <ProductKeyID>124</ProductKeyID>
                  <ProductKeyID>125</ProductKeyID>
               </Keys>";
DataContractSerializer serializer = new DataContractSerializer(typeof(Keys));
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xmlSrc)))
{

    var i = (Keys)serializer.Readobject(stream);
}

[DataContract(Namespace = "")]
[Serializable]
public class Keys
{
    [DataMember(Order = 1)]
    public List<string> ProductKeyID { get; set; }
}

如何调整 C# 类以正确反序列化 XML?

我确实搜索了帖子是否存在,但其中大部分是 json 格式,似乎对我的情况没有帮助。

解决方法

作为替代,您可以使用 CollectionDataContract 属性。您的类 Keys 将从 List 继承。在 CollectionDataContract 属性中指定根元素的名称和项目的名称。

[CollectionDataContract(Name = "Keys",ItemName = "ProductKeyID",Namespace ="")]
public class Keys<T> : List<T>
{
}

DataContractSerializer serializer = new DataContractSerializer(typeof(Keys<string>));
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xmlSrc)))
{
    var i = (Keys<string>)serializer.ReadObject(stream);
}