Search code examples
jsonapiasp.net-coreserializationdto

Return inherited DTO from API controller along with parent fields to the client


I have a parent DTO as following:

public abstract class BaseDTO
{
   public list<string> message = new list<string>();
}

and a child class:

public class MyDTO : BaseDTO
{
   public string name { get; set; }
}

now when I try to view MyDTO in swagger schema section, the message field of BaseDTO does not appear in the list of fields also when I try to

return ok(MyDTO)

in my web api controller this field is not shown on client side


Solution

  • Install Microsoft.AspNetCore.Mvc.NewtonsoftJson Nuget Package, and add the following code in Program.cs:

    builder.Services.AddMvc().AddNewtonsoftJson(options => {
        options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
    });
    

    Below is my test code, it works fine:

    Model:

    public class BaseDTO
    {
        public List<string> message = new List<string>() { "test1","test2","test3" };
    }
    
    public class MyDTO : BaseDTO
    {
        public string name { get; set; } 
    }
    

    Controller Action:

    [HttpGet]
    public IActionResult Test() 
    
        MyDTO myDTO = new MyDTO();
        myDTO.name = "name";
    
        return Ok(myDTO);
    }
    

    Test Result:

    enter image description here

    enter image description here

    If you don't want to set value in BaseDTO, you can also set myDTO.message:

    [HttpGet]
    public IActionResult Test() 
    {
        MyDTO myDTO = new MyDTO();
        myDTO.message.Add("test1");
        myDTO.message.Add("test2");
        myDTO.name = "name";
    
        return Ok(myDTO);
    }