Resolve the ASP. NET Web API JSON object Circular Reference error

Source: Internet
Author: User

Objective

In general, when we open the ASP. NET Web API, if you use the entity Framework technology to manipulate the database, when the two entity contains a navigation attribute (Navigation property), and when we output the format of the JSON object, An exception will appear with the error message: "' objectcontent ' 1 ' type cannot serialize content type ' Application/json; Charset=utf-8 ' response to the subject. , and the younger brother, referring to Brother Po and Bruce's two predecessors, sorted out two kinds of alternatives and solutions that the younger brothers found more feasible.

Understanding the problem

This picture contains two tables of Orders and Order_Details, and there is a one-to-many relationship between them, and the default Entity Framework automatically adds navigation properties (Navigation property) to our associated data table. Then we look down at the picture:

Public ienumerable<orders> getorders () {return db.         Orders; }

This program code is a Function in Valuescontroller, and when we do, we return the Orders all the data, but when we enter the URL/api/values/request, we have this error:

The reason for this problem is that when we request a particular enity, we take out all the attribute content of that Entity, and of course the data of the navigation property is covered, but how does the problem occur? In the current case, when we obtain the orders of the information will also get its navigation properties, that is order_details all the data, and in Order_Details also contains the navigation properties of orders, so will be to get orders of data ...., so that the non-stop round-tripping between two entities creates an infinite loop, which is also the error of the circular reference that we mentioned earlier.

How to Solve

Method One:

In the development of ASP, some categories (Partail Class) are often used to add validation attributes to our data domain bits, so we use this feature to solve our problem by first adding two files under the Model Data folder: OrdersMetadata.cs , Order_detailsmetadata.cs

View Sourceprint? 01. OrdersMetadata.cs 02.    03.      [MetadataType( typeof (OrderMD))] 04.      public partial class Order 05.      { 06.          public class OrderMD 07.          { 08.              [JsonIgnore()] // 需引用 using Newtonsoft.Json; 09.              public virtual ICollection<Order_details> Order_Details { get ; set ; } 10.          } 11.      }Order_DetailsMetadata.cs 12.    13.      [MetadataType( typeof (Order_DetailsMD))] 14.      public partial class Order_Details 15.      { 16.          public class Order_DetailsMD 17.          { 18.              [JsonIgnore()]  // 需引用 using Newtonsoft.Json; 19.              public virtual Orders Orders { get ; set ; } 20.          } 21.      }

Here we add the "jsonignore" property on the corresponding navigation property, to prevent the circular reference problem, remember that there are related to both sides to add "jsonignore" properties.

Method Two:

Another approach is to use the ViewModel concept that we used to develop ASP, to return only specific data for a particular page or request, so we can solve our problem through a DTO approach, first we add a DTO.cs file under the Model: Www.it165.net

DTO.cs

View Sourceprint? 01. public class OrderDTO 02. { 03.      public int OrderID { get ; set ; } 04.      public string CustomerID { get ; set ; } 05.      public int ? EmployeeID { get ; set ; } 06.      public DateTime? OrderDate { get ; set ; } 07.      public List<Order_detailsDTO> Order_Detail { get ; set ; } 08. } 09. public class Order_DetailsDTO 10. { 11.      public int OrderID { get ; set ; } 12.      public decimal UnitPrice { get ; set ; } 13.      public decimal Quantity { get ; set ; } 14. }

and modify the Function we originally had in the Web API Controller:

View Sourceprint? 01. public IEnumerable<OrderDTO> GetOrders() 02. { 03.      NorthwindEntities db = new NorthwindEntities(); 04.       05.      return db.Orders.ToList().Select(p => new OrderDTO 06.      { 07.          CustomerID = p.CustomerID, 08.          EmployeeID = p.EmployeeID, 09.          OrderDate = p.OrderDate, 10.          OrderID = p.OrderID, 11.          Order_Detail = p.Order_Details.Select(x => new Order_DetailsDTO 12.          { 13.              OrderID = x.OrderID, 14.              Quantity = x.Quantity, 15.              UnitPrice = x.UnitPrice 16.          }).ToList() 17.      }); ; 18. }

Summarize

Both methods can solve the problem of circular object reference, and in Bruce and will brother Po's article all pointed out that the first method to solve this circular reference error is the most correct approach, two approaches are two different starting points, so how to use should be to see how the reader application.

Resolve the ASP. NET Web API JSON object Circular Reference error

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.