Asp.Net Core Web API 2.2控制器未返回完整的JSON

Jac*_*ack 6 c# asp.net-core-mvc asp.net-core asp.net-core-webapi

我的Asp.Net Core Web API 2.2项目中有一个Web API Controller.

Messageboard 模型:

public class MessageBoard
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }

        public ICollection<Message> Messages { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

Message 模型:

public class Message
    {
        public long Id { get; set; }
        public string Text { get; set; }
        public string User { get; set; }
        public DateTime PostedDate { get; set; }

        public long MessageBoardId { get; set; }
        [ForeignKey("MessageBoardId")]
        public MessageBoard MessageBoard { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

这是我的Web API Controller操作之一,为简洁起见缩短了:

[Route("api/[controller]")]
[ApiController]
public class MessageBoardsController : ControllerBase
{        
      // GET: api/MessageBoards
      [HttpGet]
      public async Task<ActionResult<IEnumerable<MessageBoard>>> GetMessageBoards()
      {
         return await _context.MessageBoards
            .Include(i => i.Messages)
            .ToListAsync();
      }
}
Run Code Online (Sandbox Code Playgroud)

每当我向MessageBoards发出GET请求时,只返回部分正确的JSON.以下是https://localhost:44384/api/MessageBoards/在Postman上访问时返回的JSON :

[{"id":1,"name":"Test Board 2","description":"用于测试目的的第二个留言板.","messages":[{"id":1,"text":"发布我的第一条消息!","用户":"Jesse","postedDate":"2019-01-01T00:00:00","messageBoardId":1

JSON是截止的(因此它是一个丑陋的块并且没有被Postman美化),可能是由于模型MessageBoard上的属性,Message因为它是第一个缺少的JSON项目.

如何正确地返回MessageBoards和子消息列表?

Tan*_*jel 14

我看到你Eager Loading在查询中使用了.因此,在Startup类中添加以下配置,以忽略它在对象图中找到的循环并JSON正确生成响应.

public void ConfigureServices(IServiceCollection services)
{
    ...

    services.AddMvc()
        .AddJsonOptions(
            options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
        );

    ...
}
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息: EF Core中的相关数据和序列化