I have a MVC4 Web API service which works fine for concrete data types. But when I specify an interface as a contract and try to return the concrete type from the action, it throws an error
public interface IData
{
string NameText {get;set;}
}
[KnownType(typeof(IData))]
public class Data : IData
{
string NameText {get;set;}
}
The ‘ObjectContent`1’ type failed to serialize the response body for
content type ‘application/xml; charset=utf-8’.Consider using a DataContractResolver or add any types not known
statically to the list of known types – for example, by using the
KnownTypeAttribute attribute or by adding them to the list of known
types passed to DataContractSerializer.
I tried adding a KnownType contract over the concrete type specifying the interface type but it doesnt work.
Is it not possible to specify interfaces as DataContracts for the Service in MVC Web API? This used to work in WCF
[KnownType]is for specifying concrete classes, not interfaces. If you specify which classes implement IData with[KnownType], then at least MVC knows what types it will have to serialize/deserialize:This should do the trick!