asp.net - 如何配置 ASP.NET Core 来处理循环引用而不破坏主体的响应?

标签 asp.net asp.net-core asp.net-core-mvc asp.net-core-2.0

我有这个 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; }
        }
    }
}

当查询/api/SampleData/Demo时,我得到响应正文:

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

...这显然是非常损坏的类似 JSON 的输出。

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

最佳答案

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

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

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

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

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

关于asp.net - 如何配置 ASP.NET Core 来处理循环引用而不破坏主体的响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49350272/

相关文章:

asp.net-core - 如何从命令行运行 xunit for asp.net 5 进行单个测试

c# - 在 ASP.NET Core 和 .NET Core 控制台项目中使用相同的 `.resx` 文件

asp.net-core - userManager.CreateAsync System.ObjectDisposeException 未处理

asp.net-core-mvc - 如何在 Entity Framework 核心中导航多对多关系

c# - 使用 ASP.NET MVC 中父页面模型的内容填充 PartialView 模型

c# - 如何在c#中处理线程

c# - 使用 C# 和 tableadapter 循环结果

c# - LDAP - 检索所有属性/值的列表?

c# - .NET Core 中 Assembly.GetEntryAssembly() 的等价物是什么?

javascript - 如何在 MVC Core 中 require/reference config.json