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

时间:2021-10-14 16:41:15

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://*.com/questions/21046872/prevent-id-ref-when-serializing-objects-using-web-api-and-json-net