繁体   English   中英

如何配置ASP.NET Core来处理循环引用而不破坏正文的响应?

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

我有这个ASP.NET Core 2.0 MVC控制器:

[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; }
        }
    }
}

在查询/api/SampleData/Demo ,我得到了响应体:

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

...这显然是非常破碎的类JSON输出。

我如何以及在何处配置基于ASP.Net Core 2.0 MVC的应用程序,以使框架以不破坏输出的方式序列化循环引用? (例如,通过引入$ref$id 。)

为了打开JSON.Net序列化的引用,您应该将SerializerSettings PreserveReferencesHandling属性设置为PreserveReferencesHandling.Objects枚举值。

在ASP.Net Core中,您可以通过在Startup.ConfigureServices方法中进行以下调整来完成:

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

现在模型将被序列化为以下正确的JSON:

{
  "$id": "2",
  "name": "test",
  "demos": [ { "$ref": "2" } ]
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM