gpt4 book ai didi

c# - 从 MVC 4 Web Api 返回匿名类型失败并出现序列化错误

转载 作者:IT王子 更新时间:2023-10-29 04:47:36 28 4
gpt4 key购买 nike

我刚刚开始使用 MVC 4 Web API,我似乎误解了它的工作原理。

在使用 Web API 之前,我有一个像这样的简单 MVC 操作方法:

public JsonResult User()
{
return Json(new
{
firstName = "Joe",
lastName = "Jacobs",
email = "joe.jacobs@gmail.com"
});
}

那会很好。在新的 Web API Controller 中,我正在尝试做类似的事情。

public object User()
{
return new
{
firstName = "Joe",
lastName = "Jacobs",
email = "joe.jacobs@gmail.com"
}
}

由于序列化错误而失败:

The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.

内部异常:

Type '<>f__AnonymousType1`3[System.String,System.String,System.String]' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. If the type is a collection, consider marking it with the CollectionDataContractAttribute. See the Microsoft .NET Framework documentation for other supported types.

关于从 API Controller 返回匿名类型,我有什么不明白的地方?

最佳答案

如果你看看 Fiddler(这里的例子我用的是 Firefox)

enter image description here

默认情况下,来自浏览器的请求将接受 application/xml,而不是application/json

但是,您可以通过添加一个 header 从 Fiddler 创建假请求:

Accept: application/json

它会起作用

来自link :

The XML serializer does not support anonymous types or JObject instances. If you use these features for your JSON data, you should remove the XML formatter from the pipeline, as described later in this article.

如何删除 XmlFormatter:

  var configuration = GlobalConfiguration.Configuration;
configuration.Formatters.Remove(configuration.Formatters.XmlFormatter);

关于c# - 从 MVC 4 Web Api 返回匿名类型失败并出现序列化错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14962134/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com