c# – 为什么在web api中返回一个具有一对多关系的实体会导致错误?

前端之家收集整理的这篇文章主要介绍了c# – 为什么在web api中返回一个具有一对多关系的实体会导致错误?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一对一的关系到同一个类叫用户,
我在web apis get方法中返回一个用户实例
它工作正常,只要我没有任何
  1. User
  2.  
  3. ID | Name
  4. 0 | A
  5. 1 | B
  6.  
  7. Friends Table ( This table is used to build the one to many relationship )
  8.  
  9. User_ID | Friend_ID
  10. 1 | 0
  11. 0 | 1

这是我的GetMethod

  1. [HttpGet]
  2. public Models.User Authenticate()
  3. {
  4. try
  5. {
  6. return db.Users.SingleOrDefault(x => x.ID == 0 ) ;
  7. }
  8. catch
  9. {
  10. return null;
  11. }
  12. }

如果我得到并返回一个用户实体,那么我会得到打击错误

任何人都可以帮我修复以下错误

{“Message”:”An error has occurred.”,”ExceptionMessage”:”The ‘ObjectContent`1’ type Failed to serialize the response body for content type ‘text/html; charset=utf-8’.”,”ExceptionType”:”System.InvalidOperationException”,”StackTrace”:null,”InnerException”:{“Message”:”An error has occurred.”,”ExceptionMessage”:”Self referencing loop detected with type ‘System.Data.Entity.DynamicProxies.Friend_E5C79F4736EB2750392FFC7061B18E9C12F15F9583409603C75C5D1B1F7358D4’. Path ‘Friends1[0].User.Friends’.”,”ExceptionType”:”Newtonsoft.Json.JsonSerializationException”,”StackTrace”:” at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CheckForCircularReference(JsonWriter writer,Object value,JsonProperty property,JsonContract contract,JsonContainerContract containerContract,JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer,IWrappedCollection values,JsonArrayContract contract,JsonProperty member,JsonContainerContract collectionContract,JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer,JsonContract valueContract,JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer,JsonObjectContract contract,JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter,Object value)\r\n at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter,Object value)\r\n at Newtonsoft.Json.JsonSerializer.Serialize(JsonWriter jsonWriter,Object value)\r\n at System.Net.Http.Formatting.JsonMediaTypeFormatter.<>c__DisplayClassd.b__c()\r\n at System.Threading.Tasks.TaskHelpers.RunSynchronously(Action action,CancellationToken token)”}}

解决方法

尝试更改webApi格式化程序.在WebApiConfig.cs中添加这些行:
  1. var json = config.Formatters.JsonFormatter;
  2. json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
  3. config.Formatters.Remove(config.Formatters.XmlFormatter);

添加以下行:

  1. json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore

猜你在找的C#相关文章