如何配置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控制器:
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; }
}
}
}
查询/api/SampleData/Demo
时,我将其作为响应正文:
When querying /api/SampleData/Demo
, I get as response body:
{"name":"test","demos":[
...这显然是非常破碎的类似JSON的输出.
...which is obviously very broken JSON-like output.
我如何以及在何处配置基于ASP.Net Core 2.0 MVC的应用程序,以使框架以不破坏输出的方式序列化循环引用? (例如,通过引入$ref
和$id
.)
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
.)
推荐答案
为了打开JSON.Net序列化的引用,应将SerializerSettings
的PreserveReferencesHandling
属性设置为PreserveReferencesHandling.Objects
枚举值.
In order to switch on references for JSON.Net serialization, you should set PreserveReferencesHandling
property of SerializerSettings
to PreserveReferencesHandling.Objects
enum value.
在ASP.Net Core中,您可以通过在Startup.ConfigureServices
方法中进行以下调整来做到这一点:
In ASP.Net Core you could do it by following adjustment in Startup.ConfigureServices
method:
services.AddMvc()
.AddJsonOptions(opt =>
{
opt.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;
});
现在,该模型将被序列化为以下正确的JSON:
Now the model will be serialized to following correct JSON:
{
"$id": "2",
"name": "test",
"demos": [ { "$ref": "2" } ]
}
这篇关于如何配置ASP.NET Core以处理循环引用而不破坏主体的响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!