开发者

Serializing data using IEnumerable<T> with WebGet

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 exa开发者_Go百科ct 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


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

[WebGet]
MyClass[] WebMethod() { return OtherMethod().ToArray(); }


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜