1.提示"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; "类似这种的异常

解决方法:

在"WebApiConfig.cs"中添加如下代码

 

方式一(在"Register"方法中插入如下代码)亲自测试可以:

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

 

方式二(这个没有测过):

public static class WebApiConfig {

    public static void Register (HttpConfiguration config) {
        JsonMediaTypeFormatter jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().Single();
        jsonFormatter.UseDataContractJsonSerializer = false;
        jsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
        jsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        jsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None;
    }

}

详情参考:http://stackoverflow.com/questions/21046872/prevent-id-ref-when-serializing-objects-using-web-api-and-json-net

相关文章:

  • 2021-07-26
  • 2022-01-31
  • 2022-01-17
  • 2021-12-16
  • 2022-12-23
  • 2021-12-07
  • 2021-11-04
猜你喜欢
  • 2021-06-12
  • 2021-08-02
  • 2022-12-23
  • 2021-12-22
  • 2022-12-23
  • 2022-12-23
  • 2022-01-12
相关资源
相似解决方案