首页 > Windows开发 > 详细

在Mvc中创建WebApi是所遇到的问题

时间:2016-03-11 11:38:38      阅读:341      评论:0      收藏:0      [点我收藏+]

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

在Mvc中创建WebApi是所遇到的问题

原文:http://www.cnblogs.com/qiailu/p/5264889.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!