我有这个 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 序列化的引用,您应该将 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" } ]
}
关于asp.net - 如何配置 ASP.NET Core 来处理循环引用而不破坏主体的响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49350272/