[英]How to resolve System.Text.Json.JsonException: A possible object cycle was detected in Entity Framework?
[英]A possible object cycle was detected when serializing entity-model to JSON
我有一個使用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
}
}
]
}
}
有沒有辦法不改變輸出的結構而是忽略循環引用?
這里有一個類似的問題,其中一個答案提到了您遇到的相同問題: .Net Core 3.0 possible object cycle was detected that is not supported
那里提到的一些事情:
如果您使用的是 .NET 6,則可以使用
JsonSerializerOptions options = new()
{
ReferenceHandler = ReferenceHandler.IgnoreCycles,
WriteIndented = true
};
或者,根據您需要實現的目標,您可能只想完全忽略循環屬性。
正確的解決方案是找出引用的確切位置循環並從序列化中排除有問題的屬性,或者以不循環的格式(例如 id 或類似格式)提供它們
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.