I have a ASP.NET MVC Web API controller that returns public IEnumerable<IMessage> Get()
It throws exception that I need to register types that derive from IMessage in known types collection passed to DataContractSerializer.
How to register “Known Types” for using with DataContractSerializer and DataContractJSONSerializer in MVC Web API project?
KnownType attribute cannot be placed on interface.
You need to put the
KnownTypeAttributeon yourIMessageimplementations:So when calling the following action:
The result will be this:
But this will only work one “way”. So you cannot post back the same XML.
In order to the following action should work:
You need to register the known types globally, with configuring a
DataContractSerializerand setting up in theGlobalConfiguration.Configuration.FormattersWith using the configuration you don’t need the
KnownTypeAttributeon your implementation types.