使用 IEnumerable序列化数据与 WebGet
嗨,
如果我的方法签名看起来像这样,那么它工作得很好。
[WebGet]
MyClass[] WebMethod()
如果签名看起来像这样,
[WebGet]
IEnumerable<T> WebMethod()
我会收到以下错误: 无法序列化类型“XYZT+
我尝试过添加。 ServiceKnownType(typeof(IEnumerable))
同样的错误。
这是 2010 beta 2 中的错误吗?还是说这在未来可能是正确的?
谢谢
possible duplicate:
Cannot serialize parameter of type ‘System.Linq.Enumerable… ’ when using WCF, LINQ, JSON
Hi,
If my method signiature looks like this, it works fine.
[WebGet]
MyClass[] WebMethod()
If the signiature looks like this
[WebGet]
IEnumerable<T> WebMethod()
I get the following error:
Cannot serialize parameter of type 'X.Y.Z.T+<WebMethod>d__2c' (for operation 'WebMethod', contract 'IService') because it is not the exact type 'System.Collections.Generic.IEnumerable`1[X.Y.Z.T]' in the method signature and is not in the known types collection. In order to serialize the parameter, add the type to the known types collection for the operation using ServiceKnownTypeAttribute.
I have tried adding.
ServiceKnownType(typeof(IEnumerable))
Same error.
Is this a bug in 2010 beta 2, or is this likely to be correct going forward?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
C# 编译器生成的迭代器类型不可序列化,也永远不会。
如果您阅读此页面,您会发现序列化没有意义迭代器。
您需要返回一个数组。
编辑:最简单的方法是将迭代器移动到单独的方法,并将
WebMethod
更改为The iterator types generated by the C# compiler are not serializable and never will be.
If you read this page, you'll see that it wouldn't make sense to serialize the iterator.
You need to return an array.
EDIT: The simplest way to do that is to move your iterator to a seperate method, and change
WebMethod
to我遇到了同样的问题,就我而言,根本不可能将整个对象图从基于迭代器的 IEnumerable 更改为具体类型。我根本没有足够的内存来转换为具体类型,如列表或数组。另外,如果我返回某个具有 IEnumerable 属性的对象的 IEnumerable ,情况又如何呢?我必须递归转换所有 IEnumerable 的整个对象图,这是不可接受的。
我不认为 DataContractSerializer 无法迭代任何 IEnumerable 类型并以与任何其他集合类型相同的方式将其元素呈现为 XML,即使 IEnumerable 没有具体的支持类型也是如此。
这是一个应该修复的错误。
I've run into the same issue, and in my case it's simply not possible to change my entire object graph from iterator-based IEnumerable to concrete types. I simply cannot afford the memory to convert over to concrete types like List or Array. Additionally, what about the case where I return an IEnumerable of some object that has an IEnumerable property. It is unacceptable that I have to recurse my entire object graph converting all IEnumerables.
I don't see any good reason why the DataContractSerializer can't iterate any IEnumerable type and render its elements to XML in the same manner as any other collection type, even if the IEnumerable doesn't have a concrete backing type.
This is a bug which should be fixed.