Loading ...

WCF: Type '<>f__AnonymousType0' xxx cannot be serialized. Consider marking it with the DataContractAttribute attribute | CodeAsp.Net

WCF: Type '<>f__AnonymousType0' xxx cannot be serialized. Consider marking it with the DataContractAttribute attribute

 /5
0 (0votes)

I was working with one method in my WCF Application which was giving the following exception while calling it:

Type '<>f__AnonymousType0' xxxxxxx annot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute.  If the type is a collection, consider marking it with the CollectionDataContractAttribute.  See the Microsoft .NET Framework documentation for other supported types.

Reason:


The reason for this was that the method was returning anonymous type as one of its properties.  The response of that method was like this:

        public MyResponse DoWork()
        {
            MyResponse response = new MyResponse
            {
                MyData = new
                {
                    items = results
            };
            return response;
        }


Above "new {items=results}" (anonymous type) is the culprit.The DataContractSerializer (default serializer which is used to serialize WCF requests) can support the following cases:

  • Types serialized using the Serializable attribute.
  • Types serialized using XML Serialization.
  • Types serialized using the DataContract attribute.

and anonymous type lacks all of the above points and this is the reason why the above exception was coming while serialization of anonymous type.

Solution:

Change the anonymous type to predefined type for WCF response in above case. Make a separate class and return that as the parameter to your WCF response.

Comments (no comments yet)

Top Posts