我有这样一堂课
public class Unit
{
public int Id { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessageResourceName = "RequiredMessage", ErrorMessageResourceType = typeof(BankPhonesTextResource))]
[MaxLength(30, ErrorMessageResourceName = "MaxLengthMessage", ErrorMessageResourceType = typeof(BankPhonesTextResource))]
[RegularExpression(@"[\u0020\u200C\u202F\u0622\u0627\u0628\u067E\u062A\u062B\u062C\u0686\u062D\u062E\u062F\u0630\u0631\u0632\u0698\u0633\u0634\u0635\u0636\u0637\u0638\u0639\u063A\u0641\u0642\u06A9\u06AF\u0644\u0645\u0646\u0648\u0647\u06BE\u06CC\u0643\u064A\u0626]+", ErrorMessageResourceName = "RegularExpressionMessage", ErrorMessageResourceType = typeof(BankPhonesTextResource))]
public string Name { get; set; }
public int UnitTypeId { get; set; }
public UnitType UnitType { get; set; }
public int? ParentUnitId { get; set; }
public Unit ParentUnit { get; set; }
public virtual ICollection<Unit> SubUnits { get; set; }
public Unit()
{
SubUnits = new HashSet<Unit>();
}
}
和一个具有动作的API控制器
public async Task<ActionResult<IEnumerable<Unit>>> GetUnits()
{
return await _context.Units.ToListAsync();
}
我从邮递员那里得到了这个错误(我不使用newtonsoft json.net):
System.Text.Json.JsonException:检测到可能的对象循环。这可以是循环造成的,也可以是对象的深度大于32的最大允许深度。考虑在ReferenceHandler.Preserve上使用JsonSerializerOptions来支持循环。
请帮我修正我的密码。谢谢
发布于 2021-07-16 09:55:43
当DBSet从上下文直接返回列表而不选择某些成员时,默认的JSON序列化程序将使用所有嵌套级别序列化DBSet对象,这将生成您面临的异常,以解决此问题,您可以将此代码添加到要忽略的Startup方法中。
services.AddControllers().AddNewtonsoftJson(options =>
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
发布于 2022-07-16 09:07:17
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers().AddJsonOptions(o => o.JsonSerializerOptions
.ReferenceHandler = ReferenceHandler.IgnoreCycles);
}
https://stackoverflow.com/questions/68411528
复制