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

感情迁移 提交于 2019-12-10 17:13:37

问题


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.)


回答1:


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" } ]
}


来源:https://stackoverflow.com/questions/49350272/how-to-configure-asp-net-core-to-handle-circular-references-without-breaking-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!