Inheriting and Formatting ASP.NET Web API JSON

Imagine a simple IEnumerable<BaseType> Get() controller action. It returns an enumeration of different types, all of which are based on BaseType.

When a client requests XML, the result looks something like this:

 <ArrayOfBaseType> <BaseType i:type="DerivedType1"><A>value</A></BaseType> <BaseType i:type="DerivedType2"><B>value</B></BaseType> <BaseType i:type="DerivedType3"><C>value</C></BaseType> </ArrayOfBaseType> 

As you can see, the type of the derived class is passed in the i:type attribute.

If the client requests JSON, this information is missing:

 [ {"A":"value"}, {"B":"value"}, {"C":"value"} ] 

How to fix it?

+7
source share
2 answers

The following change is required:

In WebApiConfig.cs, add the following line:

 config.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Auto; 

This will cause a new $type property to appear if necessary.

+4
source

If you write your class as follows:

 public class MyClass { // properties here public string IType { get { return this.GetType().Name; } set { } } } 

Maybe this will help you

0
source