【发布时间】:2020-05-28 12:54:45
【问题描述】:
在我的 web api 中,当我运行从数据库获取数据的项目时出现此错误 .net 核心 3.1
JsonException:检测到不支持的可能对象循环。这可能是由于循环或对象深度大于最大允许深度 32 造成的。
这些是我的代码 我的模特
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string ProductText { get; set; }
public int ProductCategoryId { get; set; }
[JsonIgnore]
public virtual ProductCategory ProductCategory { get; set; }
}
我的 productCategory 类是:
public class ProductCategory
{
public int Id { get; set; }
public string Name { get; set; }
public string CatText { get; set; }
public string ImagePath { get; set; }
public int Priority { get; set; }
public int Viewd { get; set; }
public string Description { get; set; }
public bool Active { get; set; }
public DateTime CreateDate { get; set; }
public DateTime ModifyDate { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
我的仓库是
public async Task<IList<Product>> GetAllProductAsync()
{
return await _context.Products.Include(p => p.ProductCategory).ToListAsync();
}
我的界面
public interface IProductRepository
{
...
Task<IList<Product>> GetAllProductAsync();
...
}
这是我在 api 项目中的控制器
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
private readonly IProductRepository _productRepository;
public ProductsController(IProductRepository productRepository)
{
_productRepository = productRepository;
}
[HttpGet]
public ActionResult Get()
{
return Ok(_productRepository.GetAllProduct());
}
}
当我运行 api 项目并输入此网址时:https://localhost:44397/api/products 我得到了那个错误, 解决不了
【问题讨论】:
-
你的产品和产品类别是如何联系在一起的?
-
可能需要在从 ProductCategory 到 Product 的 FK 属性上使用
[JsonIgnore] -
我更新了我的问题,但错误存在。
-
ReferenceLoopHandling.Ignore 可能是一个选项
-
您的
ProductCategory中可能引用了Product类。然后你创建了一个参考循环。
标签: c# api asp.net-core asp.net-core-mvc