web api没有返回所有对象

时间:2014-03-27 11:28:50

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

我的web api控制器中有一个方法,如下所示:

// GET api/categories/top
[HttpGet]
[Route("api/categories/top")]
public IHttpActionResult Top()
{
    var models = service.GetRoot("Categories", "Assets").Categories;
    var t = models.Where(model => !model.Deleted);

    return Ok(t);
}

如果我运行它,我会得到第一个项目,但其他项目显示为

{"$ref":"3"},{"$ref":"13"},{"$ref":"14"},{"$ref":"15"}

如果我将代码更改为:

// GET api/categories/top
[HttpGet]
[Route("api/categories/top")]
public IHttpActionResult Top()
{
    var models = service.GetRoot("Categories", "Assets").Categories;

    return Ok(models);
}

它工作正常(但这显示所有类别,包括已删除的类别,这不是我想要的)。

有谁知道为什么会这样?

2 个答案:

答案 0 :(得分:0)

怎么样?

var models = service.GetRoot("Categories", "Assets").Categories;
var t = models.Where(model => !model.Deleted).ToList();
return Ok(t);

我希望返回一个未执行的IEnumerable对象时出现问题。

答案 1 :(得分:0)

以下是相同

的一个非常简单的示例

public class Employee
{
    public string Name { get; set; }
    public bool Deleted { get; set; }
}

样本数据

var employees = new List<Employee>();
employees.Add(new Employee{ Name = "Yasser", Deleted = false });
employees.Add(new Employee{ Name = "Hanselman", Deleted = true });
employees.Add(new Employee{ Name = "Neel", Deleted = true });
employees.Add(new Employee{ Name = "Ian", Deleted = false });

返回“未删除”列表

return employees.Where(model => !model.Deleted).ToList();

代码中所需的更改:

// GET api/categories/top
[HttpGet]
[Route("api/categories/top")]
public IHttpActionResult Top()
{
    var models = service.GetRoot("Categories", "Assets").Categories;
    var t = models.Where(model => !model.Deleted).ToList();
    return Ok(t);
}