![](/img/trans.png)
[英].Net Core 3.0 possible object cycle was detected which is not supported
[英]A possible object cycle was detected which is not supported
我知道这里有关于那个特定问题的问答,但我的问题并不独特(我猜)。
这是我的模型类:
public class RoleMaster
{
[Key]
[Required]
public int Id { get; set; }
[Required]
[StringLength(20)]
public string Role { get; set; }
}
这是我的控制器:
public class RolesController : ControllerBase
{
private readonly IRolesRepository _repo;
public RolesController(IRolesRepository repo)
{
_repo = repo;
}
[HttpGet]
public IActionResult Get()
{
var roles = _repo.GetRoles();
return new JsonResult(roles);
}
}
我的存储库:
public interface IRolesRepository
{
Task<IEnumerable<RoleMaster>> GetRoles();
}
这是 GetRoles 方法:
public async Task<IEnumerable<RoleMaster>> GetRoles()
{
try
{
var roles = await db.RoleMaster.AsNoTracking().ToListAsync();
return roles;
}
catch (Exception)
{
throw;
}
}
这是我得到的错误:
处理请求时发生未处理的异常。 JsonException: 检测到不支持的可能的对象循环。 这可能是由于循环或对象深度大于最大允许深度 32。 System.Text.Json.ThrowHelper.ThrowInvalidOperationException_SerializerCycleDetected(int maxDepth)
从其他问题我发现,如果您有其他表的引用,那么可能会发生这种错误,但在我的情况下,不涉及其他表。 这是我创建的第一个表,只是在尝试 get 方法。
_repo.GetRoles();
未使用await
关键字
这个var roles = _repo.GetRoles();
应该
var roles = await _repo.GetRoles();
你混合异步和非异步,
下面未经测试,但你应该得到 jist
[HttpGet]
public async Task<IActionResult> Get()
{
var roles = **await** _repo.GetRoles();
return new JsonResult(roles);
}
仅供参考 - 我原来的答案实际上是正确的.... objectA 是... Task
,因为那是从_repo.GetRoles();
返回的_repo.GetRoles();
您的对象 A 引用了引用对象 A 的对象 B。
这只是以递归循环结束,基本上永远不会结束尝试序列化。
可能的对象循环
此外,您没有包含可能抛出 JsonResult 异常的代码,因此看不到您使用的序列化程序。
此外,如果您使用的是 newtonJson,那么对复杂对象的支持就更加有限。
进一步 - 只是一个基于 q 的 FYI 注释非异步版本,因为如果你不想改变它,你的主(控制器)线程不是异步的,如上所述或为了清楚起见
public List<RoleMaster> GetRoles()
{
try
{
var roles = db.RoleMaster.AsNoTracking().ToList();
return roles;
}
catch (Exception)
{
throw;
}
}
更新以获取更多指导
https://docs.microsoft.com/en-us/aspnet/core/web-api/action-return-types?view=aspnetcore-3.1
我有同样的问题。
这就是解决我的问题的原因:
将 JsonIgnore 属性放在引用属性上(导致无休止的序列化)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.