![](/img/trans.png)
[英]JsonException: A possible object cycle was detected which is not supported. This can either be due to a cycle or if the object depth is larger than
[英]A possible object cycle was detected. This can be due to a cycle or if the object depth is larger than the maximum allowed depth of 32
我遇到了非常奇怪的情況。 我正在開發一個 net 5 api,並且(在其他實體中)有三個表,Doctor、Specialization 和 DoctorSpecialization。 我的實體:
public class Doctor
{
public int Id { get; set; }
public string Name { get; set; }
public string Resume { get; set; }
public ICollection<DoctorSpecialization1> DoctorSpecializations { get; set; }
}
public class DoctorSpecialization
{
public int Id { get; set; }
public int Doctor1Id { get; set; }
[ForeignKey("Doctor1Id")]
public Doctor1 Doctor { get; set; }
public int Specialization1Id { get; set; }
[ForeignKey("Specialization1Id")]
public Specialization1 Specialization { get; set; }
}
public class Specialization
{
public int Id { get; set; }
public string SpecializationName { get; set; }
}
我想獲取與某個醫生相關的所有專業,因此我創建了一個服務:
public class DoctorService : IDoctorService
{
public async Task<List<Specialization>> GetAllSpecializationsForDoctor(int id)
{
var doctor = await _context.Doctors.Where(x => x.Id == id).FirstOrDefaultAsync();
var doctorSpecializations = await _context.DoctorSpecializations.
Where(x => x.DoctorId == doctor.Id)
.ToListAsync();
IEnumerable<int> ids = doctorSpecializations.Select(x => x.SpecializationId);
var specializations = await _context.Specializations.Where(x =>
ids.Contains(x.Id)).ToListAsync();
return specializations;
}
}
最后,我在我的控制器中添加了一個方法,它應該根據醫生的 id 獲取專業:
[HttpGet("specializations/{id}")]
public async Task<ActionResult<List<Specialization1>>> GetSpecializationsForDoctor(int id)
{
var doctor = await _doctorService.FindDoctorById(id);
if (doctor == null) return NotFound();
var specialization = _doctorService.GetAllSpecializationsForDoctor(id);
return Ok(specialization);
}
當我在郵遞員中運行此程序時,出現此問題標題中所述的錯誤。 但是,我遇到了一篇文章,其中解釋了我應該安裝 newtonsoft.json 並在我的 Startup 中進行一些更改以解決此問題。 因此,我安裝了 Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="5.0.10" 並在我的 Starup 中進行了如下更改:
services.AddControllers().AddNewtonsoftJson(options =>
options.SerializerSettings.ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Ignore);
這次我得到了預期的結果,但是我的郵遞員在給我想要的結果之前顯示了大量數據,我想知道將這么多數據返回給客戶端是否可以。 有人可以提前向我解釋這是怎么回事嗎?
顯然解決方案很簡單,我錯過了等待:
var specialization = await
_doctorService.GetAllSpecializationsForDoctor(id);
由於stackoverflow,我再次設法找到了解決方案,因為顯然其他人遇到了這個問題: JsonException:檢測到不支持的可能的對象循環。 這可能是由於循環或對象深度大於
所以請大家不要像我一樣膚淺,一定要使用 await 並節省您的時間。 再次感謝社區:)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.