Polymorphism for return type in dotnet REST API

Viewed 454

In context of a dotnet core REST api, I want to return a 'light' version of objects when listing them to avoid a lot of unacessary data. I try to use polymorphism to do so :

public class Person
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
}
public class Student : Person
{
  public int Age { get; set; }
}

[HttpGet("testList")]
public List<Person> getPersons()
{
  List<Person> testList = new List<Person>();
  testList.Add(new Student() { FirstName = "Kevin", LastName = "Smith", Age = 99 });
  return testList;
}

[HttpGet("test")]
public Student getStudent()
{
  return new Student() { FirstName = "Kevin", LastName = "Smith", Age = 99 };
}

When I call /testList, I got the following json :

[
  {
    "age": 99,
    "firstName": "Kevin",
    "lastName": "Smith"
  }
]

I was expecting return to not contain age parameter due to return type, but it's not the case. Is there a way to get a 'light version' only for the listing method ?

Thank you,

2 Answers

I recommend to use Data Transfer Objects (DTOs) to return only the information you want. Use it like this:

[HttpGet("testList")]
public List<PersonDto> getPersons()
{
  List<Person> testList = new List<Person>(); // ... fetch records from data source

  return testList.Select(e => new PersonDto() { // PersonDto contains only props you need
    FirstName = e.FirstName,
    LastName = e.LastName
  });
}

When we use inheritance, we must remember that the child object can be replaced by the parent object, and you have done exactly the same here, and when it becomes to json, the real type of objects is considered, not their abstract type. You can return parent object like this:

public static List<Person> getPersons()
{
  List<Person> testList = new List<Person>();
  testList.Add(new Student() { FirstName = "Kevin", LastName = "Smith", Age = 99 });
  return testList.Select(e=> new Person() {FirstName=e.FirstName,LastName=e.LastName}).ToList();
}

And i think good idea is using Dto's,As our friend @TWP mentioned above.

Related