gpt4 book ai didi

c# - dotnet REST API 中返回类型的多态性

转载 作者:行者123 更新时间:2023-12-04 10:04:06 25 4
gpt4 key购买 nike

在 dotnet 核心 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com