【问题标题】:JSon seralization error with Web ApiWeb Api 的 JSON 序列化错误
【发布时间】:2015-08-26 20:26:56
【问题描述】:

我收到一个自引用循环错误“检测到类型为 'ASP.global_asax' 的属性 'ApplicationInstance' 的自引用循环”从对 Web api 的 PUT 调用返回。

我将此添加到 web api 配置中:

        GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.All;

现在我得到一个不同的错误:

“‘ObjectContent`1’类型未能序列化内容类型‘application/json’的响应正文;charset=utf-8 InnerException":ExceptionMessage":"从 'System.Web.HttpInputStream' 上的 'ReadTimeout' 获取值时出错。","ExceptionType":"Newtonsoft.Json.JsonSerializationException","StackTrace":" 在 Newtonsoft.Json.Serialization.DynamicValueProvider .GetValue(对象目标)...

根据建议,我添加了“.ReferenceLoopHandling.Ignore;”配置。这修复了循环错误,但没有修复“无法读取值”错误。 我很难找到治疗这个的方法。

编辑 - 错误消失了。我还犹豫说它是否已修复,因为我还不确定为什么首先会出现错误。我通过在 web api 中更改我的 Put 代码使错误离开。那是:

    [HttpPut]
    public IHttpActionResult Put([FromBody]RecipientDTO recipient)
    {
        try
        {
            repo.SaveUpdatedRecipient(recipient);
            return Ok(this.GetById(recipient.RecipKey));
        }
        catch (Exception ex)
        {
            return BadRequest(ex.ToString());
        }
    }

现在是:

    [HttpPut]
    public HttpResponseMessage Put([FromBody]RecipientDTO recipient)
    {
        try
        {
            repo.SaveUpdatedRecipient(recipient);
            return Request.CreateResponse(HttpStatusCode.OK);
        }
        catch (Exception ex)
        {
            ex.ToString();
            //ValidationMethods.GetDbValidationExceptions(ex);
            return Request.CreateResponse(HttpStatusCode.NotFound);
        }
    }

我仍在处理错误处理部分,但至少错误消失了,数据被保存了。当我发现更多时,我会更新。欢迎任何意见。

【问题讨论】:

  • 如果你尝试这个:GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
  • 谢谢,但没有改变。
  • 你的 PUT 调用是什么样的?
  • 也不明白,但您更改为 HttpResponseMessage 也为我做了。我一直对 IHttpActionResult 帮助者持怀疑态度,但这是我第一次遇到这个问题。 “感觉”就像 Newstonsoft jsonserializer 的特定版本在响应链的某个地方出现问题。

标签: asp.net-web-api httpclient


【解决方案1】:

要解决此问题,请将以下代码行添加到您的 webapi 项目中的 WebApiConfig.cs 文件中

config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多