asp-net web api 序列化嵌套列表

1 c# asp.net asp.net-web-api

我有返回产品列表的 api 方法:getAllProduct()返回填充列表,包括:

List<Product> dependProduct
Run Code Online (Sandbox Code Playgroud)

但客户端收到一个空的dependProduct.

public class Product
{
    public string Title { get; set; }
    public int Cost { get; set; }
    public List<Product> dependProduct = new List<Product>();

}
Run Code Online (Sandbox Code Playgroud)

控制器:

[Route("~/Shop/Product")]
[ResponseType(typeof(IEnumerable<Product>))]
public HttpResponseMessage Get()
{
        var data = getAllProduct(); //  has dependProduct 
        return this.Request.CreateResponse(HttpStatusCode.OK, data);
}

private List<Product> getAllProduct()
{
  return context.Products.ToList();
}
Run Code Online (Sandbox Code Playgroud)

客户:

var request = new RestRequest("/Shop/Product", Method.GET);
var response = client.Execute<List<Product>>(request);
return response.Data;  // has not dependProduct  why?
Run Code Online (Sandbox Code Playgroud)

Ily*_*lya 5

我认为问题在于dependProduct声明为字段而不是属性。尝试将产品更改为

public class Product
{
   public Product()
   {
      dependProduct = new List<Product>();
   }

    public string Title { get; set; }
    public int Cost { get; set; }
    public List<Product> dependProduct { get; set; }
}
Run Code Online (Sandbox Code Playgroud)