简体   繁体   中英

ASP.NET MVC4 Web API Interfaces as Data Contract

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:

[KnownType(typeof(MyDataThingy1))]
public class MyDataThingy1 : IData
{ ... }

[KnownType(typeof(MyDataThingy2))]
public class MyDataThingy2 : IData
{ ... }

This should do the trick!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM