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
.)
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" } ]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With