从 MVC 4 Web Api 返回匿名类型失败并出现序列化错误 [英] Returning an anonymous type from MVC 4 Web Api fails with a serialization error

查看:20
本文介绍了从 MVC 4 Web Api 返回匿名类型失败并出现序列化错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm just getting started with MVC 4 Web API and I seem to be misunderstanding how it works.

在 Web API 之前,我有一个简单的 MVC 操作方法,如下所示:

Before Web API I had a simple MVC action method like this:

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

那会工作得很好.在新的 Web API 控制器中,我正在尝试做类似的事情.

That would work fine. In the new web API controller I am trying to do something similar.

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

由于序列化错误而失败:

This fails with a serialization error:

ObjectContent`1"类型未能序列化内容类型application/xml"的响应主体;字符集=utf-8'.

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

内部异常:

类型 '<>f__AnonymousType1`3[System.String,System.String,System.String]' 无法序列化.考虑使用 DataContractAttribute 特性标记它,并使用 DataMemberAttribute 特性标记要序列化的所有成员.如果类型是集合,请考虑使用 CollectionDataContractAttribute 对其进行标记.有关其他支持的类型,请参阅 Microsoft .NET Framework 文档.

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 控制器返回匿名类型有什么不理解?

What am I not understanding about returning anonymous type from the API controller?

推荐答案

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

If you look at the Fiddler (sample in here I use Firefox)

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

By default, request from browser will accepts application/xml, not application/json

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

But, you can create fake request from Fiddler by adding one header:

Accept: application/json

它会起作用

来自 链接:

XML 序列化程序不支持匿名类型或 JObject 实例.如果您将这些功能用于 JSON 数据,您应该从管道中删除 XML 格式化程序,如本文后面所述.

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);

这篇关于从 MVC 4 Web Api 返回匿名类型失败并出现序列化错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆