4

I am using WCF WebAPI to write REST services using WCF. I am returning my POCO classes as json/xml objects from my service. Most of my POCO classes contain ICollections as they are part of EF4.1 Code First, hence I get error :

Cannot serialize member of type ... System.Collections.Generic.ICollection ... because it is of type - because it is an interface

To avoid that XMLIgnore and ScriptIgnore is suggested. And there are some problems in custom serialization of JSON in WCF.

Just thought someone might have come across a similar problem and have a better solution or way to configure serialization classes, otherwise I will have to decorate each such attribute with XMLIgnore, etc.

Community
  • 1
  • 1
Anand
  • 4,523
  • 10
  • 47
  • 72

4 Answers4

3

More often than not you probably would use DTOs or (view models in ASP.NET MVC) to decouple from your domain model. And you can use AutoMapper to minimize your code converting between domain models and DTOs.

misaxi
  • 568
  • 2
  • 10
  • +1 to this response. WCF WebAPI isn't really in the business of providing rich entities across the wire, it's more focused on RESTful interactions and representations of data. All of my WCF WebAPI expose purposefully-crafted DTOs that represent just the data necessary for the request. – ckittel Aug 09 '11 at 01:15
  • Thanks, I understand this, but the reason I wrote those REST svc is for Cloud Database sync with in-premise DB, hence I am sending EF POCO entity as it is. – Anand Jul 24 '12 at 06:39
2

You have to add [XmlIgnore] and [IgnoreDataMember]. Then the property will be ignored for xml and json response.

1

Thats right Sandro, [IgnoreDataMember] and [XmlIgnore] is needed.

A little bit more explaination: [IgnoreDataMember] is needed to exclude the field in json serialization, [XmlIgnore] is needed to exclude the field in xml serialization.

SeriousM
  • 3,374
  • 28
  • 33
0

I found that in WCF WebAPI [ScriptIgnore] or [JsonIgnore] are not working and have no effect, so I'm going back to ASP.NET MVC for json-related REST APIs.

Update[24-Jul-2012] This answer is old, and Microsfot WebAPI has come a long way since, please check before relying on this answer.

Anand
  • 4,523
  • 10
  • 47
  • 72