【问题标题】:Why am I getting this WCF Error Message?为什么我会收到此 WCF 错误消息?
【发布时间】:2015-08-04 19:55:41
【问题描述】:

我在调用 WCF 服务时收到以下错误。我在这里错过了什么?

'System.String[]' with data contract name
'ArrayOfstring:http://schemas.microsoft.com/2003/10/Serialization/Arrays'
is not expected. Add any types not known statically to the list of known
types - for example, by using the KnownTypeAttribute attribute or by adding
them to the list of known types passed to DataContractSerializer.'.  Please
see InnerException for more details.

{"There was an error while trying to serialize parameter
http://tempuri.org/:myEntity. The InnerException message was
'Type 'System.String[]' with data contract name
'ArrayOfstring:http://schemas.microsoft.com/2003/10/Serialization/Arrays'
is not expected. Add any types not known statically to the list of known
types - for example, by using the KnownTypeAttribute attribute or by adding
them to the list of known types passed to DataContractSerializer.'.  

Please see InnerException for more details."}

【问题讨论】:

  • 您可以将代码发布到您的服务和/或客户端吗?
  • 我是 WCF 的新手...myEntity 是一个 C# 业务对象...您能告诉我如何以及在哪里将这种类型提供给 DataContractSerializer 吗?

标签: wcf web-services


【解决方案1】:

据我所知,您有一个 WCF 函数,它有一个名为“myEntity”的参数。我假设 myEntity 的类型是一个用户定义的类,并用 DataContract 属性装饰,因为它应该是。我还假设 myEntity 的类型有一个成员字段,它是一个字符串数组。让我们假设所有这些都是真的(同样,如果您可以发布您的代码,这将非常有帮助)。

通常,字符串数组,即 string[],可以很好地序列化。但是,在某些情况下(请参阅 herehere),您可能必须将其添加到已知类型列表中,以便 WCF 正确序列化所有内容。

为此,请添加以下内容:

[DataContract]
[KnownType(typeof(string[]))]
public class YourClassNameHere
{
}

【讨论】:

  • 击中目标马特...就像一个魅力!:-)谢谢你的回答!
  • 我得到这个错误并且我没有自定义类怎么办?我只想传递一个恰好是字符串[]的参数。
【解决方案2】:

您还没有发布代码,所以我的回答是基于假设您有一个 myEntity 类,您正在尝试序列化。尝试为类使用 KnownTypeAttribute

例如

[KnownType(typeof(myEntity))]

您可以参考以下 MSDN 链接: KnownTypeAttribute

【讨论】:

    【解决方案3】:

    是的。如上一篇文章所述,如果您传递一个类型的数组(定义为 DataContract]),则会出现此问题。您需要将此类的数组定义为单独的类型并将其标记为数据协定。

    不会工作`

    [DataContract]
    Public class ABC{
    }
    
    ...
    
    SendData(ABC[])
    

    `

    什么会起作用:

    Public class Data{ public ABC[] prop{get;set;}}
    ...
    SendData(Data);
    

    【讨论】:

      【解决方案4】:

      在我的例子中,在将 [Serializable] 属性添加到 MyEntity 类之后。然后问题是角色字符串数组的序列化。

          [Serializable]
          [KnownType(typeof(string[]))]
          public class MyEntity
          {
             .........
             public string roles[]
             ......... 
          }
      

      [KnownType(typeof(string[]))] 像魔术一样工作!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-25
        • 1970-01-01
        • 1970-01-01
        • 2022-12-03
        • 1970-01-01
        • 2018-06-22
        • 2016-01-01
        相关资源
        最近更新 更多