Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure ASP.NET Core to handle circular references without breaking the body's response?

I have this ASP.NET Core 2.0 MVC Controller:

[Route("api/[controller]")]
public class SampleDataController : Controller
{
    [HttpGet("[action]")]
    public Example Demo()
    {
        return new Example("test");
    }

    public class Example
    {
        public Example(string name)
        {
            Name = name;
        }

        public string Name { get; }

        public IEnumerable<Example> Demos
        {
            get { yield return this; }
        }
    }
}

When querying /api/SampleData/Demo, I get as response body:

{"name":"test","demos":[

...which is obviously very broken JSON-like output.

How and where do I have to configure my ASP.Net Core 2.0 MVC-based app to make the framework serialize circular references in a way that does not break the output? (For example, by introducing $ref and $id.)

like image 357
Hauke P. Avatar asked Mar 18 '18 16:03

Hauke P.


1 Answers

In order to switch on references for JSON.Net serialization, you should set PreserveReferencesHandling property of SerializerSettings to PreserveReferencesHandling.Objects enum value.

In ASP.Net Core you could do it by following adjustment in Startup.ConfigureServices method:

services.AddMvc()
    .AddJsonOptions(opt =>
    {
        opt.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;
    });

Now the model will be serialized to following correct JSON:

{
  "$id": "2",
  "name": "test",
  "demos": [ { "$ref": "2" } ]
}
like image 73
CodeFuller Avatar answered Sep 24 '22 23:09

CodeFuller