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

return data in json format in web api
asp.net core json formatter
asp.net core 2.2 return json
.net core return status code with message
web api return json string
asp.net core web api routing
web api return both json and xml
asp.net return 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?

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

Format response data in ASP.NET Core Web API, For example, returning JsonResult returns JSON-formatted data. ASP.NET Core supports any object return value. Results from actions that return objects that are not IActionResult types are serialized using the appropriate IOutputFormatter For more information, see Controller action return types in ASP. .net core 2.2 Web Api not returning any messages, Status code returned fine Hot Network Questions Does being "paralyzed" grant the effects of a rest

Try to create and return a DTO or a new struct/class that will not have cyclic info (MessageBoard has Message that has MessageBoard etc...)

Create web APIs with ASP.NET Core, ASP.NET Core supports creating RESTful services, also known as web APIs, using C#. Controllers in a web API are classes that derive from ControllerBase . support for views, so it's for handling web pages, not web API requests. If compatibility version is set to 2.2 or later, the [ApiController] attribute� I am developing an API with ASP.NET Core and I am struggling with the exception handling. When any exception occurs, or in any controller where I want to return custom errors with different status

The selected answer was correct in my case as well, my JSON response was getting truncated by a reference loop in my JSON response, and setting ReferenceLoopHandling.Ignore did indeed solve my issue. However, this is not the best solution in my opinion, as this maintains the circular references in your model. A better solution would use the [JsonIgnore] attribute within the model.

The issue in your model is here:

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

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

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 the cause of your circular referece!!!
    }  

As you can see, your MessageBoard navigation property is where this response is truncated. Specifically, it will cause each Message in the json response to contain all of the MessageBoard information for each Message entry in the response. Newtonsoft does not like this. The solution is to simply [JsonIngore] the navigation properties that cause this circular reference. In your code this would be:

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

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

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

        [JsonIgnore]
        [ForeignKey("MessageBoardId")]
        public MessageBoard MessageBoard { get; set; } //fixed!!!
    }  

Handling errors in ASP.NET Core Web API, NET Core Web API projects and how these approaches differ from MVC error Web API have been combined so you now have the same controllers for both MVC If a client passes you invalid data, returning a 400 Bad Request is not going to A missing ProductId results in a 400 status code plus a JSON response body� An action isn't required to return any specific type. ASP.NET Core supports any object return value. Results from actions that return objects that are not IActionResult types are serialized using the appropriate IOutputFormatter implementation. For more information, see Controller action return types in ASP.NET Core web API.

ASP.NET Core Web API app returning JSON instead of XML, NET Core Web API app not returning XML? It is always returning JSON. When I specify "[Produces("application/xml")]" attribute in my controller,� If the [ApiController] attribute in ASP.NET Core 2.1 or later is applied, model validation errors result in a 400 status code. For more information, see Automatic HTTP 400 responses. ActionResult<T> type. ASP.NET Core 2.1 introduced the ActionResult<T> return type for web API controller actions.

Formatting Response Data - ASP.NET Core Documentation, ASP.NET Core MVC has built-in support for formatting response data, using fixed Results from actions that return objects that are not IActionResult types will be the Controller base class, use the built-in helper method Json to return JSON and Unlike typical API clients, web browsers tend to supply Accept headers that� JSON Patch in ASP.NET Core. The ASP.NET Core implementation of JSON Patch is provided in the Microsoft.AspNetCore.JsonPatch NuGet package. Action method code. In an API controller, an action method for JSON Patch: Is annotated with the HttpPatch attribute. Accepts a JsonPatchDocument<T>, typically with [FromBody].

Create a web API with ASP.NET Core MVC, This tutorial teaches the basics of building a web API with ASP.NET Core. NET Core SDK 2.2 or later. Visual Studio NET Core Web Application - TodoApi dialog, choose the ASP.NET Core Defines an API controller class without methods. Decorates Otherwise, the method returns 200 with a JSON response body. In this article, I will demonstrate how we can customize ASP.NET Web API Media Formatter and retrieve the data in a format as we want like XML or JSON. I will retrieve data from the SQL database and format them in JSON format. XML is default format in ASP.NET Web API. Step 1 Open SQL Server 2014 or your choice create a table insert some records.

Comments
  • Serializing objects with null properties to json is not an unexpected occurrence and is completely supported by pretty much all frameworks. Not sure what serializer you're using but you might want to swap it out to see if that was the cause, and if it was, open a bug report.
  • @Will I am using the default Web API Serializer. I haven't changed any serialization settings since creating the project.
  • Have you checked how you configured your serializer to deal with circular dependencies? It seems to me that once the serializer reaches the circular dependency, it just stops the serialization (Maybe an exception?)
  • @RicardoAlves I hadn't configured it was the issue. I applied Tanvir's configuration and the circular dependency was fixed.
  • This would be my first guess of where the problem is.
  • Yes! If JSON response in ASP.NET Core return incomplete data then this is one of the main reason.
  • Awesome, this is what I was looking for. I added this to my Startup.cs and it works correctly now. I figured there was a simple fix for this, I just didn't know what it was. I will accept this answer when the timer is up. Thank you!
  • That's a nice solution, but the best would be not to send DB objects to the clients, create proper Viewmodels, map the necessary fields without back referencing fields.
  • Dang. I know that that is the issue, I was just hoping there was a simple way for Web API to handle it without having to create new classes.