.net core : incomplete JSON response

2019-06-16 03:58发布

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":"n.bouh@test.com","password":"nico@hotmail.fr","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

2条回答
相关推荐>>
2楼-- · 2019-06-16 04:37

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;
    });
}
查看更多
做个烂人
3楼-- · 2019-06-16 04:48

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.

查看更多
登录 后发表回答