问题描述
在我的 web api 中,当我运行从数据库获取数据的项目时出现此错误.net 核心 3.1
In my web api when i run project for get data from database got this error .net core 3.1
JsonException:检测到不支持的可能对象循环.这可能是由于循环或对象深度大于最大允许深度 32 造成的.
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 the maximum allowed depth of 32.
这些是我的代码我的模特
These are my code my Model
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 类是:
my productCategory class is:
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 项目中的控制器
and this is my controller in api project
[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我得到了那个错误,解决不了
When I run api project and put this url: https://localhost:44397/api/products I got that error , I cant resolve it
推荐答案
这是因为你的数据有一个引用循环.
this is happening because your data have a reference loop.
例如
// this example creates a reference loop
var p = new Product()
{
ProductCategory = new ProductCategory()
{ products = new List<Product>() }
};
p.ProductCategory.products.Add(p); // <- this create the loop
var x = JsonSerializer.Serialize(p); // A possible object cycle was detected ...
你还不能在新的 System.Text.Json
中处理引用循环情况(netcore 3.1.1),除非你完全忽略一个引用并且它总是不是一个好主意.(使用 [JsonIgnore]
属性)
You can not handle the reference loop situation in the new System.Text.Json
yet (netcore 3.1.1) unless you completely ignore a reference and its not a good idea always. (using [JsonIgnore]
attribute)
但您有两种选择来解决此问题.
but you have two options to fix this.
您可以使用
Newtonsoft.Json
在您的项目中,而不是System.Text.Json
(我为您链接了一篇文章)
you can use
Newtonsoft.Json
in your project instead ofSystem.Text.Json
(i linked an article for you)
从 dotnet5 库(通过 Visual Studio 的 NuGet 客户端)下载 System.Text.Json
预览包版本 5.0.0-alpha.1.20071.1
:
Download the System.Text.Json
preview package version 5.0.0-alpha.1.20071.1
from dotnet5 gallery (through Visual Studio's NuGet client):
选项 1 用法:
services.AddMvc()
.AddNewtonsoftJson(
options => {
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
// if you not using .AddMvc use these methods instead
//services.AddControllers().AddNewtonsoftJson(...);
//services.AddControllersWithViews().AddNewtonsoftJson(...);
//services.AddRazorPages().AddNewtonsoftJson(...);
选项 2 用法:
// for manual serializer
var options = new JsonSerializerOptions
{
ReferenceHandling = ReferenceHandling.Preserve
};
string json = JsonSerializer.Serialize(objectWithLoops, options);
// -----------------------------------------
// for asp.net core 3.1 (globaly)
services.AddMvc()
.AddJsonOptions(o => {
o.JsonSerializerOptions
.ReferenceHandling = ReferenceHandling.Preserve
});
这些序列化程序具有 ReferenceLoopHandling
功能.
these serializers have ReferenceLoopHandling
feature.
- 编辑:
ReferenceHandling
在 DotNet 5 中更改为ReferenceHandler
- Edit :
ReferenceHandling
changed toReferenceHandler
in DotNet 5
但如果您决定只忽略一个引用,请在这些属性之一上使用 [JsonIgnore]
.但即使您没有引用循环,它也会导致您对该字段的 API 响应为空.
but if you decide to just ignore one reference use [JsonIgnore]
on one of these properties. but it causes null result on your API response for that field even when you don't have a reference loop.
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string ProductText { get; set; }
public int ProductCategoryId { get; set; }
// [JsonIgnore] HERE or
public virtual ProductCategory ProductCategory { get; set; }
}
public class ProductCategory
{
public int Id { get; set; }
// [JsonIgnore] or HERE
public ICollection<Product> products {get;set;}
}
这篇关于JsonException:检测到不支持的可能对象循环.这可能是由于循环或对象深度大于的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!