why In web api returning an entity that has a one to many relationship causes an error?

后端 未结 2 1973
臣服心动
臣服心动 2020-12-24 15:42

Guys I have a One to many relation to same class called user,
I am returning one instance of user in web apis get method it works fine as far as I don\'t have any

相关标签:
2条回答
  • 2020-12-24 16:16

    Try to change webApi formatter. Add these lines in WebApiConfig.cs:

    var json = config.Formatters.JsonFormatter;
    json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
    config.Formatters.Remove(config.Formatters.XmlFormatter);
    

    And add this line:

    json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
    
    0 讨论(0)
  • 2020-12-24 16:27

    Apply the [JsonIgnore] attribute to the navigation property you don't want to be serialised. It will still serialise both the parent and child entities but just avoids the self referencing loop.

    0 讨论(0)
提交回复
热议问题