【问题标题】:Failed to serialize the response body for content type 'application/xml; charset=utf-8'未能序列化内容类型“application/xml”的响应正文;字符集=utf-8'
【发布时间】:2017-02-01 10:42:03
【问题描述】:

我有一个相当简单的控制器。我的错误是“application/xml”,不像重定向给我的问题是“application/json”。

public class ProductController : ApiController
{
        private IProductService productservice = new ProductServices();

        public List<Employee> Get()
        {
            return productservice.GetProducts();
        }
    }
}

但我仍然收到以下错误。

“ObjectContent`1”类型无法序列化内容类型“application/xml;”的响应正文; charset=utf-8'。

我尝试了以下方法,但没有成功。

  1. 在 WebApiConfig.cs 中添加了这个

    var json = config.Formatters.JsonFormatter;
    json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
    config.Formatters.Remove(config.Formatters.XmlFormatter);
    
  2. 在 Global.asax.cs 中添加这个

    GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
    GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize;
    

【问题讨论】:

标签: http asp.net-web-api


【解决方案1】:
  1. 从 WebApiConfig.cs 中删除

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

然后粘贴下一个代码:

var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

并丢弃 Global.asax.cs 中的更改

【讨论】:

    猜你喜欢
    • 2020-02-28
    • 2015-06-27
    • 2012-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-13
    • 1970-01-01
    • 2012-12-12
    相关资源
    最近更新 更多