1

我的 wcf webservice 中定义了两种类型。DynamicFieldsClassA

[DataContract]
[KnownType(typeof(ClassA[]))]
public class DynamicFields
{
    [DataMember]
    public Dictionary<string, object> properties = new Dictionary<string, object>();

    public object this[string name]
    {
        get
        {
            if (properties.ContainsKey(name))
            {
                return properties[name];
            }
            return null;
        }
        set
        {
            properties[name] = value;
        }
    }
}

[DataContract]
public class ClassA
{
    [DataMember]
    public int Id { get; set; }

    ...
}

当我将服务添加为客户端中的服务引用时,我得到了System.ServiceModel.Dispatcher.NetDispatcherFaultException

类型异常

“System.ServiceModel.Dispatcher.NetDispatcherFaultException”发生在 mscorlib.dll 中,但未在用户代码中处理

附加信息:格式化程序在尝试反序列化消息时抛出异常:尝试反序列化参数http://tempuri.org/:GetResultsResult时出错。InnerException 消息是“第 1 行位置 3900 中的错误。元素“ http://schemas.microsoft.com/2003/10/Serialization/Arrays:Value ”包含来自映射到名称“ http://schemas ”的类型的数据.datacontract.org/2004/07/SomeNamespace:ArrayOfClassA'。反序列化器不知道映射到此名称的任何类型。如果您正在使用 DataContractSerializer,请考虑使用 DataContractResolver,或者将与“ArrayOfClassA”对应的类型添加到已知类型列表中 - 例如,通过使用 KnownTypeAttribute 属性或将其添加到传递给序列化程序的已知类型列表中。有关更多详细信息,请参阅 InnerException。

我查看了客户端自动生成的 reference.cs 文件,发现 KnownType 属性不存在

[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="DynamicFields", Namespace="http://schemas.datacontract.org/2004/07/SomeNamespace")]
[System.SerializableAttribute()]
public partial class DynamicFields : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged {

    ...
}

[KnownType(typeof(ClassA))]然后我在reference.cs中手动添加属性并且它可以工作

[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="DynamicFields", Namespace="http://schemas.datacontract.org/2004/07/SomeNamespace")]
[System.SerializableAttribute()]
[KnownType(typeof(ClassA[]))] //This is what I manually added
public partial class DynamicFields : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged {

    ...
}

这里的问题是每次更新服务引用,都需要去reference.cs手动添加knowntype属性。有没有办法让客户端自动生成它?

4

0 回答 0