4

I have a new project with .Net Core. It's a WebAPI project. And I have a separate project for my model.

In WebAPI project, in a controller, I have something like this:

    // GET: api/questions
    [HttpGet]
    public IEnumerable<Question> GetQuestions()
    {
        return _context.Questions
            .Include( i => i.QuestionType );
    }

When I call http://localhost:55555/api/questios/ it just returns the first record, and then this error message: Recv failure: Connection was reset

If I remove the Include part and just return the _context.Questions, it work just fine!

What's wrong in my code?

Rahmani
  • 857
  • 3
  • 14
  • 28

2 Answers2

13

I've found the answer. Thank you everyone who helped.

I added json options according to Loading related data

If you are using ASP.NET Core, you can configure Json.NET to ignore cycles that it finds in the object graph. This is done in the ConfigureServices(...) method in Startup.cs.

            services.AddMvc()
              .AddJsonOptions(
                    options => options.SerializerSettings.ReferenceLoopHandling
                        = Newtonsoft.Json.ReferenceLoopHandling.Ignore );
Rahmani
  • 857
  • 3
  • 14
  • 28
  • 2
    I found this solved my problem, but then I found another way which I think I prefer. I added the `[JsonIgnore]` decorator to the properties that I didn't want to serialize and there were no longer any loops to worry about. I suspect this is usually the reference from a child back to its parent. See this answer for more details: https://stackoverflow.com/a/11851461/5322405 – Ken Lyon May 01 '18 at 18:26
  • Awesome addition, @KenLyon. I'm not yet sure this is my exact problem here, but I've been using `ReferenceLoopHandling.Ignore` and much prefer the decorator solution. – Auspex Jan 16 '19 at 16:57
  • 1
    Ah! I discovered that I did, in fact, have `ReferenceLoopHandling.Ignore` set in `services.AddMvc()`, but because I had added `JsonSerializerSettings` in a _specific_ Json() call, it was being overridden. – Auspex Jan 16 '19 at 17:19
0

Try this:

// GET: api/questions
[HttpGet]
public IEnumerable<Question> GetQuestions()
{
    var res = _context.Questions
        .Include( i => i.QuestionType ).ToArray();
    return res;
}
Andreas Zita
  • 7,232
  • 6
  • 54
  • 115