【发布时间】:2021-12-03 21:42:22
【问题描述】:
我有一个使用 C# 编写并构建在 ASP.NET Core/5 框架之上的 webapi 项目。
API 返回 JSON 数据。
这是一个端点的示例
[HttpGet]
public async Task<ActionResult<TModel[]>> QueryAsync(
[FromQuery(Name = "filter")] string filter = null,
[FromQuery(Name = "expand")] string expand = null)
{
IQueryable<TModel> query = GetQuery(filter, expand);
var models = await query.ToArrayAsync();
return Ok(models);
}
在上述请求中,expand 将告诉服务器要扩展哪些导航属性。当用户请求扩展属性时,我收到以下错误
A possible object cycle was detected. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32. Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles
按照错误的指示,我在 Startup 类中添加了以下内容
services.AddControllers().AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
// added this
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve;
});
上述更改确实解决了问题!然而,它引入了另一个问题。新的问题是它改变了输出的结构。
输出来自这样的东西
{
// properties
"relations": [
{
// relation 1
"parent": null
},
{
// relation 2
"parent": null
}
]
}
这样的事情
{
"$id": "1",
// properties
"relations": {
"$id": "2",
"$values": [
{
// relation 1 properties
"$id": "3",
"parent": {
"$ref": 1
}
},
{
// relation 2 properties
"$id": "3",
"parent": {
"$ref": 1
}
}
]
}
}
有没有办法不改变输出结构而忽略循环引用?
【问题讨论】:
标签: c# json asp.net-core json.net asp.net-core-webapi