Reputation: 811
I'm writing a web service and I am attempting to add a response to a Get request. The difficulty is, I have multiple types that need to be returned. So initially I have a base class of:
public abstract class AbstractSource
{
public string name { get; set; }
}
followed by two derivatives:
public class DatabaseSource : AbstractSource
{
}
and
public class WebSource : AbstractSource
{
}
These classes will eventually have more of their own specific elements. In my controller class I have the following test code:
public class DataSourcesController : ApiController
{
AbstractSource[] sources = new AbstractSource[]
{
new WebSource { name="WebPath"},
new DatabaseSource{name="DB Source"}
};
public IEnumerable<AbstractSource> GetAllDataSources()
{
return sources;
}
}
Now when I run this I get a serializationException. Is it even possible to return mulitple types like this?
Upvotes: 0
Views: 488
Reputation: 10175
Sounded like you are trying to use get the data in XML.
The XML Serializer (e.g. the DataContractSerializer
) doesn't know how to deserialize AbstractSource
into either DatabaseSource
or WebSource
, and so you will need to snap the [KnownType(...)]
attributes on your AbstractSource
class:
using System.Runtime.Serialization;
[KnownType(typeof(DatabaseSource))]
[KnownType(typeof(WebSource))]
public abstract class AbstractSource
{
public string name { get; set; }
}
Upvotes: 2