在WebApi 2中检测到属性的自引用循环。
在WebApi 2中检测到属性的自引用循环。
我创建了一个WebApi来将新产品和评论保存到数据库中。以下是WebApi的代码:
POST api/Products
[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); }
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; } //导航属性 public ICollectionReviews { get; set; } }
Review类
public class Review { public int ReviewId { get; set; } public int ProductId { get; set; } [Required] public string Title { get; set; } public string Description { get; set; } //导航属性 public Product Product { get; set; } }
我正在使用谷歌浏览器扩展程序“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'.
如何解决这个错误?