Thursday, August 20, 2009

Code: 'Type' was not expected. Use the XmlInclude or SoapInclude attribute

I received the following error today while developing a web service:

System.InvalidOperationException: The type <CLASSNAME> was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically. 

This error was thrown because I was attempting to return an inherited class as a web service response.  There are a couple ways around this issue.

1. (My fix) Return the base class instead of the inherited class (obviously not always an option)
2. Add XmlInclude attributes to your BASE class as such:
[XmlInclude(typeof(InheritedClassName1))]
[XmlInclude(typeof(InheritedClassName2))]

3.  Write your own serialization code.