MAURICIO SIERRA
MAURICIO SIERRA

Reputation: 85

ASP.NET Core MVC/WEB API with self-referencing type does not return json array

Hello WEB API developers!

I have problems when I try to return array object with my WEB API in MVC6.

On the debug controller, I obtain two or more objects but the result only sends a response with one object. I don't know what more to do for resolve this problem. Please help me!

My controller method:

[HttpGet]
    public IEnumerable<Maquina> Get()
    {
        var maquinas = _cobraAppContext.Maquina
            .Include(m => m.IdMarcaMotorNavigation)
            .Include(m => m.IdModeloNavigation)
            .ToList();
        return maquinas;//Two or more object obtains :(
    }

Response with only 1 object, but my controller debug show me more than one:

[
  {
    "id": 1,
    "nombre": "M1",
    "idModelo": 3,
    "serie": "123456",
    "idMarcaMotor": 3,
    "serieMotor": "123456789",
    "descripcion": "ejemplo 123",
    "fechaCreacion": "2016-12-06T08:30:51.307",
    "idMarcaMotorNavigation": {
      "id": 3,
      "nombre": "DAEWO",
      "descripcion": "DAEWO",
      "fechaCreacion": "2016-11-29T15:17:33.223",
      "maquina": []
    }
  }
]

Postman

Controller debug

enter image description here

Upvotes: 8

Views: 967

Answers (2)

Nadeem Khoury
Nadeem Khoury

Reputation: 937

Change your method signature to IHttpActionResult and your controller to ApiController method like this:

 public IHttpActionResult Get()
    {
        var maquinas = _cobraAppContext.Maquina
            .Include(m => m.IdMarcaMotorNavigation)
            .Include(m => m.IdModeloNavigation)
            .ToList();
        return Ok(maquinas);//Two or more object obtains :(
    }

Upvotes: -2

raphaelheitor
raphaelheitor

Reputation: 174

Try another aproach(in Configuration method, Startup.cs):

services.AddMvc().AddJsonOptions(options => {
            options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
        });

Upvotes: 4

Related Questions