ObjectResult 包含 ASP.NET MVC6 Web Api 中的对象列表

ObjectResult containing list of objects in ASP.NET MVC6 Web Api

我正在着手使用 MVC 6 创建 API。我有几个简单的响应模型,我正在使用 ObjectResult,如下所示:

[Route("api/foos")]
public class FooController : Controller
{
    [HttpGet]
    public IActionResult GetFoos()
    {
        return new ObjectResult(FooRepository.GetAll().Select(FooModel.From));
    }
}

FooModel 是一个包含一些属性甚至简单类型列表(如字符串)的简单模型时,此方法工作正常。

但是,我现在尝试遵循类似的模式,其中 FooModel 包含其中的其他对象列表,我想在我的 [=28= 中显示这些格式良好的详细信息] 响应,作为对象数组。但是,通过以下 类 我得到 "No response recieved".

public class FooModel
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public List<Bar> Bars { get; set; }
    public FooModel(Guid id, string name, List<Bar> bars)
    {
        this.Id = id;
        this.Name = name;
        this.Bars = bars;
    }
    internal static FooModel From(Foo foo)
    {
        return new FooModel(foo.Id, foo.Name, foo.Bars);
    }
}

public class BarModel
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public BarModel(Guid id, string name)
    {
        this.Id = id;
        this.Name = name;
    }
    internal static BarModel From(Bar bar)
    {
        return new BarModel(bar.Id, bar.Name);
    }
}

如果我将 List<Bar> 更改为字符串列表,响应会很好地显示 JSON 字符串数组。如何在我的 JSON 响应中获得对 return 内部对象列表作为对象数组的响应?

我设法得到了我想要的效果,但我不确定为什么会这样 - 如果有人知道为什么,请分享!我认为 List<Bar> 没有序列化为 Bar 对象数组的原因是因为 Bar 在不同的项目中(因为它是我解决方案的更深(域)层的一部分) .当我更改 FooModel 以引用 BarModel 的列表并通过更改 FooModel 以使用静态 BarModel.From 方法填充此列表来填充它时,它会起作用,如下所示:

public class FooModel
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public List<BarModel> Bars { get; set; }
    public FooModel(Guid id, string name, List<Bar> bars)
    {
        this.Id = id;
        this.Name = name;
        this.Bars = bars.Select(BarModel.From).ToList();
    }
    internal static FooModel From(Foo foo)
    {
        return new FooModel(foo.Id, foo.Name, foo.Bars);
    }
}

如果您的 类 在使用 EntityFramework CodeFirst 方法时看起来像这种常见设置

public class Foo
{
    ...
    public int Id {get; set;}
    public IEnumerable<Bar> Bars {get;set;}
    ...
}

public class Bar
{
    ...
    public int FooId {get;set;}
    public Foo Foo {get;set;}
    ...
}

Foo 由于引用循环而无法序列化。 对于 API 到 return 正确序列化的 JSON 您必须在 Bar-class 中为 Foo-Property 添加 [JsonIgnore] 属性:

public class Bar
{
    ...
    public int FooId {get;set;}

    [JsonIgnore]
    public Foo Foo {get;set;}
    ...
}

这是假设您使用 NewtonsoftJson 作为序列化程序。

感谢@KiranChalla 在@Ivans 回答中的评论。这为我指明了正确的方向。