How to send Collection of abstract types with ActionResult

185 Views Asked by At

I am trying to send back a collection of abstract types in a Controller using ActionResult.I do not know how to tell the serializer to also include derived type(s) specific properties:

public abstract class Base
{
    public int Id{get;set;}
}
public class D1:Base
{
    public string D1Value{get;set;}
}
public class D2:Base
{
    public bool IsD2Value{get;set;}
}

public async Task<ActionResult<IEnumerable<Base>>> GetAll()
{
   var collection=new []{ new D1 {  Id=1, D1Value="hi"} ,new D2 {Id=2, IsD2Value=true}};
   return StatusCode(200,collection);
}

How can i reach this result in a easy and elegant way.I have checked the JsonSerializer options but in my case i am not the one that is doing the serialization.

What i get

[{ "Id":1} ,  { "Id":2 }]

What i want

[{ "Id":1,"D1Value":"hi" } ,  { "Id":2 , "IsD2Value":true }]
2

There are 2 best solutions below

2
On

Try the following code:

 public async Task<ActionResult<IEnumerable<Base>>> GetAll()
        {
             var collection = new List<object>() 
             { 
                 new D1 { Id = 1, D1Value = "hi" }, 
                 new D2 { Id = 2, IsD2Value = true } 
             };
            return StatusCode(200, collection);
        }

Here is the test result: enter image description here

0
On

Use new ArrayList() instead of List.