Here’s a neat little thing I learned today. I was writing a WebMethod for a WebService I’m working on for ScribbleLive. The return type is an array of Post objects.
[WebMethod]
public Post[] GetPostsSince( int ThreadId, DateTime Since )
{ ... }
But sometimes the array actually has objects of the type Comment, that is a derived class of Post. When I tried tried it out, it threw this exception:
System.InvalidOperationException: There was an error generating the XML document. —> System.InvalidOperationException: The type Comment was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.
The problem is that the Serializer doesn’t know about the Comment class until runtime, and it throws a tantrum. Luckily, the fix is just to put a directive in there to make sure it knows that the Comment class may be used.
In my case, I just added the XmlInclude directive right about my Post class declaration like this:
[Serializable()]
[XmlInclude( typeof( Comment ) )]
public class Post
{ ... }
And that did the trick! I hope this is helpful for someone else ![]()
Tags: C#, programming, webservice
Thank man!!
You save my life.