在 dotnet core REST api 的上下文中,我想在列出对象时返回对象的“轻量”版本,以避免大量不必要的数据。我尝试使用多态性来做到这一点:
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 };
}
当我调用 /testList
时,我得到了以下 json :
[
{
"age": 99,
"firstName": "Kevin",
"lastName": "Smith"
}
]
由于返回类型,我期望返回不包含 age
参数,但事实并非如此。
有没有办法获得仅适用于列表方法的“轻型版本”?
谢谢,
最佳答案
我建议使用数据传输对象 (DTO) 来仅返回您想要的信息。像这样使用它:
[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
});
}
关于c# - dotnet REST API 中返回类型的多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61675976/