.net: incomplete JSON response

I am new to .net core 2, I am trying to create a simple API for training, in my databse I got users (first name, last name, email password, list) and sport (first name, user ID) It's all right when I want to get of my users, I have an object inhabited by sports. But the JSON answer is incomplete, it is "cut off" 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 will happen if you have an idea

Thanks x

+4
source share
2 answers

I had this problem in one of my projects. This is caused by a self-regulatory cycle.

You need to create some kind of DTO (data transfer object) that will be used to create your JSON.

DTO , -

    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<Sport> Sports { get; set; }
    }

User Sport UserDto SportDto AutoMapper. , , .

Dtos JSON, .

+2

. / JSON ,

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().AddJsonOptions(options => {
        options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
    });
}
+1

Source: https://habr.com/ru/post/1689643/


All Articles