从WebAPI返回多态性列表
我正在使用.NET 6.0中的WebAPI构建一个小型简单的休息服务,
我有一个带有几个属性的基类客户。然后,我有三个从中继承的类,所以让我们称它们为TypeAclient,TypeBclient和typecclient。每个都有几个与该类型客户端相关的属性。
我有几个端点
API/customer/{customerId}/clients/{clientId}
api/customers/{customerId}/clients
第一个检索单个客户端记录,而第二个则检索了所有客户端的列表。
当我调用第一个客户(返回单个客户端)时,它始终显示适合客户端类型的属性,即,如果是一个类型的客户端,它显示了从基类继承的属性以及特定于类型的属性。
但是,如果我调用第二个,我会得到客户端对象的列表,但是每个对象仅包含从基类继承的属性。
为什么这两种方法在这方面的行为有所不同,并且有没有办法将其包括在列表中的所有属性?
下面我的控制器类的剪切版本。
谢谢!
[Route("api/customers/{customerId}/clients")]
[Authorize]
[ApiController]
public class ClientsController : ControllerBase {
[HttpGet]
public ActionResult<IEnumerable<Client>> GetClients(int customerId) {
// Retrieve data
return Ok(clients);
}
[HttpGet("{clientId}", Name = "GetClient")]
public ActionResult<Client> GetClient(int customerId, int clientId) {
// Retrieve data
return Ok(client);
}
}
I'm building a small simple REST service using WebAPI in .NET 6.0
I have a base class, Client, with a couple of properties. Then I have three classes that inherit from it, so let's call them TypeAClient, TypeBClient, and TypeCClient. Each have a couple of properties that are only relevant to that type of client.
I have a couple of endpoints
api/customers/{customerId}/clients/{clientId}
api/customers/{customerId}/clients
The first retrieves a single Client record and the second retrieves a list of all Clients for a specific customer.
When I call the first one (returns a single client), it always shows the right properties for the type of client, i.e. if it's a type A client, it shows the properties inherited from the base class and the properties specific to type A.
But if I call the second one, I get a list of Client objects, but each object only contains the properties that are inherited from the base class.
Why are the two methods behaving differently in this respect, and is there a way to get it to include all the properties in the list?
Cut-down version of my controller class below.
Thanks!
[Route("api/customers/{customerId}/clients")]
[Authorize]
[ApiController]
public class ClientsController : ControllerBase {
[HttpGet]
public ActionResult<IEnumerable<Client>> GetClients(int customerId) {
// Retrieve data
return Ok(clients);
}
[HttpGet("{clientId}", Name = "GetClient")]
public ActionResult<Client> GetClient(int customerId, int clientId) {
// Retrieve data
return Ok(client);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
找到一个有效的答案,尽管我不确定这是正确的方法还是软糖。
如果我将客户端对象的列表转换为对象列表,则串行器在列表中的每个元素上调用getType,并且输出包含特定于单个子类的属性。
Found an answer that works, although I'm not sure if it's the correct way to do it, or a fudge.
If I convert my list of Client objects to a list of object objects, then the serialiser calls GetType on each individual element in the list, and the output includes the properties that are specific to the individual subclasses.