gpt4 book ai didi

c# - ApiController 能否返回一个包含其他对象集合的对象?

转载 作者:行者123 更新时间:2023-11-30 13:39:31 26 4
gpt4 key购买 nike

如果我有一个只有简单属性(例如 Name 等)的 Customer 类,那么我可以创建一个派生的 CustomersController来自 ApiController,并使用 URL /api/customers 查询我的 Customer 对象。

同样,如果我有一个具有简单属性(DescriptionAmount)的 Order 类,那么我可以创建一个 OrdersController 并以相同的方式访问它。

但是,如果我随后向我的 Customer 类添加一个属性,该类列出与该 Customer 关联的 Order:

public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
// ...
public virtual ICollection<Order> Orders { get; set; }
}

...然后,当我尝试使用 /api/customers 进行查询时,出现 500 服务器错误。我可以在 CustomersController 中放置一个断点,并且可以看到它确实调用了正确的方法,并尝试返回一个值。然而,在框架内部的某个地方,它无法将其转换为 HTTP 响应。

看起来它无法序列化 Orders 信息和/或将其打包用于 HTTP 响应,但我不确定我需要做什么才能实现这一点。或者只是 WebApi 的东西不是为了返回复杂对象而设计的?


更新:我的代码在这里:https://gist.github.com/43ed2f29f8adfb44cef6


更新 2:关于我得到的错误的更多信息:

Server error
The website encountered an error while retrieving http://localhost:1031/api/customers/6.

It may be down for maintenance or configured incorrectly. Here are some suggestions: Reload this webpage later. HTTP Error 500 (Internal Server Error): An unexpected condition was encountered while the server was attempting to fulfill the request.

Intellitrace 日志显示以下内容:http://i.imgur.com/iHxJl.png

[我简直不敢相信 Intellitrace 窗口不允许我复制文本,以至于我不得不实际打印屏幕并上传图像。今年是哪一年?]


相关:ASP.Net Web API showing correctly in VS but giving HTTP500

最佳答案

您传递的 Entity Framework 实体会导致问题。您需要数据传输对象来传递和接收数据。因为您将实体绑定(bind)在一起,所以它不允许您序列化数据。

关于c# - ApiController 能否返回一个包含其他对象集合的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11600734/

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