Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 794
MAURICIO SIERRA Avatar asked Dec 06 '16 14:12

MAURICIO SIERRA


1 Answers

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

services.AddMvc().AddJsonOptions(options => {
            options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
        });
like image 190
raphaelheitor Avatar answered Sep 28 '22 00:09

raphaelheitor