ienumerableserializationwebget

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 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


Solution

  • 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(); }