Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.net core : incomplete JSON response

I'm trying to build simple API for training, in my database I got users (firstname, lastname, email password, list<sports>) and sports ( name, userID). All is okay when I want to get my users, I got an object populated with sports. But the JSON response is incomplete, it is "cut" in the middle.

[{"firstName":"Nicolas","lastName":"Bouhours","email":"[email protected]","password":"[email protected]","sports":[{"name":"Trail","userId":1

This is my controller :

// GET: api/Users
[HttpGet]
public IEnumerable<User> GetUsers()
{
    var users = _context.Users.Include(u => u.Sports).ToList();
    return users;
}

And my models :

public class Sport : BaseEntity
{
    public string Name { get; set; }

    public int UserId { get; set; }
    public User User { get; set; }
}

public class User : BaseEntity
{
    public String FirstName { get; set; }
    public String LastName { get; set; }
    public String Email { get; set; }
    public String Password { get; set; }

    public List<Sport> Sports { get; set; }
}

public class SportAppContext : DbContext
{
    public SportAppContext(DbContextOptions<SportAppContext> options) : base(options)
    { }

    public DbSet<User> Users { get; set; }
    public DbSet<Sport> Sports { get; set; }
}

I really don't understand what happen, if you have any idea

like image 599
Nicolas B Avatar asked Nov 21 '17 18:11

Nicolas B


People also ask

What is return type of jsonresult in ASP NET Core?

For example, returning JsonResult returns JSON-formatted data and returning ContentResult returns plain-text-formatted string data. An action isn't required to return any specific type. ASP.NET Core supports any object return value.

How to get JSON formatter response with a body of null?

The JSON formatter returns a response with a body of null. The XML formatter returns an empty XML element with the attribute xsi:nil="true" set. In the query string or part of the path. By using a format-specific file extension such as .xml or .json. The mapping from request path should be specified in the route the API is using.

What is the default JSON formatter in ASP NET Core?

In ASP.NET Core 3.0 or later, the default JSON formatters are based on System.Text.Json. Support for Newtonsoft.Json based formatters and features is available by installing the Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet package and configuring it in Startup.ConfigureServices. Show activity on this post.

How to add support for httpresponseexception in core ASP NET?

In ASP.NET 4.x Web API, one way to do this was using the HttpResponseException type. ASP.NET Core doesn't include an equivalent type. Support for HttpResponseException can be added with the following steps: The preceding filter specifies an Order of the maximum integer value minus 10.


2 Answers

I'm running into the same issue right now. You can also change the JSON serialization/configuration settings to ignore self-reference loops, as shown in the accepted answer for this question

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().AddJsonOptions(options => {
        options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
    });
}
like image 55
Amanduh Avatar answered Oct 17 '22 06:10

Amanduh


I had this problem to in one of my projects. This is caused by a self referencing loop.

You need to create some sort of DTO (Data Transfer Object) which will be used to generate your JSON.

In your DTO you remove the inverse relationship so you end up having something like

    public class SportDto
    {
        public string Name { get; set; }
    }

    public class UserDto
    {
        public String FirstName { get; set; }
        public String LastName { get; set; }
        public String Email { get; set; }
        public String Password { get; set; }

        public List<SportDto> Sports { get; set; }
    }

You then map your user User and Sport models to your UserDto and SportDto A good tool for doing this mapping is AutoMapper. You can read the docs to see how to get started.

After the mapping is done, you Send the DTOs as your JSON and not your models.

like image 20
mojoblanco Avatar answered Oct 17 '22 07:10

mojoblanco