Asp.Net Core WebApi returning object list

0

I'm trying to return a list of a "Plan" Template which has a list of "Expenses", returning only the list of plan works, but when I add to return the list of expenses of an error in javascript.

"Failed to load resource: net :: ERR_SPDY_PROTOCOL_ERROR"

"Uncaught (in promise) TypeError: Failed to fetch"

Controller

    [HttpPost]
    public IEnumerable<Plano> GetPlanos()
    {
        return db.GetPlanos()
            .AsEnumerable();
    } 

Expenses Model

[DataContract]
public class Gastos
{
    [DataMember]
    public long Id { get; set; }
    [DataMember]
    public string Descricao { get; set; }
    [DataMember]
    public TipoFrequencia Frequencia { get; set; }
    [DataMember]
    public TipoGasto Tipo { get; set; }
    [DataMember]
    public DateTime? Data { get; set; }
    [DataMember]
    public double Valor { get; set; }
    [DataMember]
    public Plano Planos { get; set; }
}

Plan Template

[DataContract]
public class Plano
{
    [DataMember]
    public long Id { get; set; }      
    [DataMember]
    public List<Gasto> Gasto { get; set; }
    [DataMember]
    public int Moradores { get; set; }

}

Call in javascript

componentDidMount() {
    fetch('Plano/GetPlanos', { method: 'POST' })
        .then(response => response.json())
        .then(data => {
            console.log(data);
            this.setState({ lista: data, loading: false });
        });   
}

Query in database

    public IQueryable<Plano> GetPlanos()
    {
        return _contexto.Planos
                    .Include(p => p.Gastos);                        
    }

Not even this console.log runs, the error happens before, if I take [DataMember] from the list of expenses it works.

asked by anonymous 04.11.2018 / 00:38

1 answer

1

Leo, this seems like a mistake to me circular reference which generally generates exception at the time of serialization. Add the line below in the ConfigureServices method of the Startup.cs class, this tends to solve this problem:

services.AddMvc()
    .AddJsonOptions(
        options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
    );
    
06.11.2018 / 14:07