zoukankan      html  css  js  c++  java
  • 在Mvc中创建WebApi是所遇到的问题

    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
  • 相关阅读:
    Python M3 面向对象
    Python 基础
    Python 基础
    Python 基础
    Python 作业
    Python 基础
    Python 基础
    【机器学习】周志华 读书笔记 第三章 线性模型
    【机器学习】周志华 读书笔记 第二章 模型评估与选择
    【机器学习】周志华 读书笔记 第一章 绪论
  • 原文地址:https://www.cnblogs.com/qiailu/p/5264889.html
Copyright © 2011-2022 走看看