문제

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

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top