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

标签 c# json rest .net-core

在 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/

相关文章:

c# - AuthenticationTypes.SecureSocketsLayer 和 AuthenticationTypes.Secure 之间有什么区别?

c# - 流利的 nHibernate 加入

c# - 人气算法

java - 在Java中解析具有特殊字符的JSON对象

java - 如何在 JAX-RS 中为子资源中的子资源设计路径?

c# - 带 bool 值的开关盒

javascript - 将数组和其他变量一起转换成 JSON

android - 删除特殊字符时,replaceAll 函数不起作用

java - 如何使用 token 安全地连接到 RESTHeart

java - 从 Spring REST Web 服务以 JSON/XML 形式抛出异常