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

时间:2014-04-01 21:01:27

标签: c# asp.net asp.net-web-api

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

List<Product> dependProduct

但客户端收到空dependProduct

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

}

控制器:

[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();
}

客户端:

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

1 个答案:

答案 0 :(得分:3)

我认为问题在于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; }
}