Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
575 views
in Technique[技术] by (71.8m points)

c# - Asp.Net Core Web API 2.2 Controller not returning complete JSON

I have a Web API Controller in my Asp.Net Core Web API 2.2 project.

Messageboard model:

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

        public ICollection<Message> Messages { get; set; }
    }

Message model:

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; }
    }

This is one of my Web API Controller actions, shortened for brevity:

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

Whenever I issue a GET request to MessageBoards, only part of the correct JSON is returned. Here is the returned JSON from accessing https://localhost:44384/api/MessageBoards/ on Postman:

[{"id":1,"name":"Test Board 2","description":"A 2nd Message board for testing purposes.","messages":[{"id":1,"text":"Posting my first message!","user":"Jesse","postedDate":"2019-01-01T00:00:00","messageBoardId":1

The JSON is cut-off (hence why it's an ugly block and not beautified by Postman), presumably due to the MessageBoard property on the Message model since it is the first missing JSON item.

How can I make the action correctly return the list of MessageBoards and child Messages?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I see you are using Eager Loading in your query. So add the following configuration in your Startup class to ignore cycles that it finds in the object graph and to generate JSON response properly.

public void ConfigureServices(IServiceCollection services)
{
    ...

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

    ...
}

For more details: Related data and serialization in EF Core


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...