【问题标题】:WCF: An error while trying to serialize parameter of List / Array typeWCF:尝试序列化列表/数组类型的参数时出错
【发布时间】:2016-10-06 17:00:11
【问题描述】:

我想在运行时获取可用的数据合约类型,这就是我使用ServiceKnownType 属性的原因:

[ServiceContract]
[ServiceKnownType("GetKnownTypes", typeof(KnownTypesProvider))]
public interface IService1
{
    [OperationContract]
    object GetData(bool list);
}
public static class KnownTypesProvider
{
    public static IEnumerable<Type> GetKnownTypes(ICustomAttributeProvider provider)
    {
        return new[] { typeof(CompositeType) };
    }
}

我从GetData方法返回CompositeType时没有问题,但是返回列表(List&lt;CompositeType&gt;)或数组(CompositeType[])会导致序列化错误:

public class Service1 : IService1
{
    public object GetData(bool list)
    {
        return list ?
            // serialization error
            (object)new List<CompositeType>() :
            // successfull result
            new CompositeType();
    }
}

错误是:

尝试序列化参数时出错 http://tempuri.org/:GetData。 InnerException 消息是 '类型'System.Collections.Generic.List`1 [[WcfService2.CompositeType,WcfService2,版本= 1.0.0.0,文化=中性,PublicKeyToken=null]]' 带有数据合同名称 'ArrayOfCompositeType:http://schemas.datacontract.org/2004/07/WcfService2' 预计不会。将任何静态未知的类型添加到列表中 已知类型 - 例如,通过使用 KnownTypeAttribute 属性 或通过将它们添加到传递给的已知类型列表中 DataContractSerializer。

我认为 WCF 默认支持集合序列化。我错过了什么吗?

如何解决这个问题?

【问题讨论】:

    标签: c# wcf serialization


    【解决方案1】:

    您可以返回List&lt;CompositeType&gt;() 而不是object。在这种情况下,您不需要使用knowntype

    尝试将您的方法更改为

            public List<CompositeType> GetData1(bool list)
            {
                return new List<CompositeType>();
                // successfull result
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多