gpt4 book ai didi

c# - 在 WebApi 2 中检测到属性的自引用循环

转载 作者:行者123 更新时间:2023-11-30 19:23:46 25 4
gpt4 key购买 nike

我创建了一个 Web Api 来将新产品和评论保存在数据库中。下面是 WebApi 代码:

POST api/产品

[ResponseType(typeof(Product))]
public IHttpActionResult PostProduct(Product product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}

db.Products.Add(product);
db.SaveChanges();

return CreatedAtRoute("DefaultApi", new { id = product.ProductId }, product);
}

产品类别

public class Product
{
public int ProductId { get; set; }
[Required]
public string Name { get; set; }
public string Category { get; set; }
public int Price { get; set; }
//Navigation Property
public ICollection<Review> Reviews { get; set; }
}

复习课

public class Review
{
public int ReviewId { get; set; }
public int ProductId { get; set; }
[Required]
public string Title { get; set; }
public string Description { get; set; }
//Navigation Property
public Product Product { get; set; }
}

entity diagram

我正在使用 google chrome 扩展程序“POSTMAN”来测试 api。当我尝试通过在 POSTMAN 中创建 POST 请求来保存详细信息时:

{
"Name": "Product 4",
"Category": "Category 4",
"Price": 200,
"Reviews": [
{
"ReviewId": 1,
"ProductId": 1,
"Title": "Review 1",
"Description": "Test review 1",
"Product": null
},
{
"ReviewId": 2,
"ProductId": 1,
"Title": "Review 2",
"Description": "Test review 2",
"Product": null
}
]
}

显示以下错误:

"Message":"An error has occurred.",
"ExceptionMessage":"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.",
"ExceptionType":"System.InvalidOperationException",
"StackTrace":null,
"InnerException":{
"Message":"An error has occurred.",
"ExceptionMessage":"Self referencing loop detected for property 'Product' with type 'HelloWebAPI.Models.Product'.

我该如何解决这个错误?

最佳答案

首先,将 Navigation 属性更改为 virtual,这将提供延迟加载,

public virtual ICollection<Review> Reviews { get; set; }

// In the review, make some changes as well
public virtual Product Product { get; set; }

其次,既然您知道 Product 不会总是在集合中有评论,那么您不能将它设置为可为 null 吗? — 只是说。

现在回到你的问题,处理这个问题的一个非常简单的方法就是忽略无法序列化的对象......再次!使用 Json.NET 的 JsonSerializer 中的 ReferenceLoopHandling.Ignore 设置来执行此操作。对于 ASP.NET Web API,可以进行全局设置(取自 this SO thread ),

GlobalConfiguration.Configuration.Formatters
.JsonFormatter.SerializerSettings.Re‌​ferenceLoopHandling
= ReferenceLoopHandling.Ignore;

这个错误来自 Json.NET,当它试图序列化一个已经被序列化的对象(你的对象循环!)时,文档也非常清楚,

Json.NET will ignore objects in reference loops and not serialize them. The first time an object is encountered it will be serialized as usual but if the object is encountered as a child object of itself the serializer will skip serializing it.

引用自 http://www.newtonsoft.com/json/help/html/SerializationSettings.htm

关于c# - 在 WebApi 2 中检测到属性的自引用循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45329513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com