【问题标题】:Self referencing loop detected for property in Web Application为 Web 应用程序中的属性检测到自引用循环
【发布时间】:2016-11-27 18:23:45
【问题描述】:

我正在尝试将移动服务应用程序移植到 Web 应用程序。为此,我创建了一个新的 Web 应用程序,并将相关代码从工作移动服务复制到我创建的新 Web 应用程序(使用移动应用程序模板。
我在新应用程序的 Startup 方法中有以下代码:

 public partial class Startup
{
    public static void ConfigureMobileApp(IAppBuilder app)
    {
        HttpConfiguration config = new HttpConfiguration();

        new MobileAppConfiguration()
            .UseDefaultConfiguration()
            .ApplyTo(config);

        // Use Entity Framework Code First to create database tables based on your DbContext
        Database.SetInitializer(new MobileServiceInitializer());
        config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;


        config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize;
        config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
        app.UseWebApi(config);
        MobileAppSettingsDictionary settings = config.GetMobileAppSettingsProvider().GetMobileAppSettings();
   }
}

config.Formatters 是从原始应用程序复制的,该应用程序将实体及其子项返回到 api 控制器的 json 输出。

在新应用程序中,我必须将 [MobileAppController] 添加到我的 api 控制器中。我从 Web 应用程序应用程序中的控制器收到以下错误:为属性团队检测到自引用循环 (模型有 Teams --> Players 和 player 有一个 teamid)

基于这个详细的问题: Self referencing loop detected - Getting back data from WebApi to the browser

上面的代码应该像在我的移动服务应用程序中一样工作。 Web 服务应用程序似乎忽略了 config.Formatters 值,因为我已经尝试了上述问题中的每个值,但我仍然得到相同的错误。
如果我将 [JSON Ignore] 属性放在子列表之前,那么我不会收到错误,也不会让子项返回 json。如何让这个 Web 应用程序接受格式值?

【问题讨论】:

  • 或者,您可以直接向您的类添加属性,例如JsonPropertyAttribute.ItemIsReference 强制PreserveReferencesHandling 用于集合项。
  • 感谢您提供有用的 cmets。感谢@dbc 向我指出这个问题。我找了3天也没找到。所以显然我是正确的,移动应用程序忽略了 json 格式化程序。你让我来这篇文章[json net error]。在 DTO 以最少的代码解决问题之前添加属性 [JsonObject(IsReference = true)]。 [json 网络错误]:stackoverflow.com/questions/7397207/…
  • @HaimKatz 这应该是一个答案而不是评论......这让我很头疼。

标签: c# json asp.net-web-api web-application-project


【解决方案1】:

感谢您提供有用的 cmets。感谢@dbc 向我指出这个问题。我找了3天也没找到。所以显然我是正确的,移动应用程序忽略了 json 格式化程序。你让我来这篇文章[json net error]。在 DTO 以最少的代码解决问题之前添加属性 [JsonObject(IsReference = true)]。 [json 网络错误]:stackoverflow.com/questions/7397207/... – Haim Katz 7 月 24 日 13:41

【讨论】:

  • 按着墨者要求
猜你喜欢
  • 1970-01-01
  • 2018-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-31
  • 2021-12-26
  • 1970-01-01
  • 1970-01-01
  • 2012-11-10
相关资源
最近更新 更多