Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

c# - Returning an anonymous type from MVC 4 Web Api fails with a serialization error

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

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

public JsonResult User()
{
    return Json(new
    {
        firstName = "Joe",
        lastName = "Jacobs",
        email = "[email protected]"
    });
}

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 = "[email protected]"
    }
}

This fails with a serialization error:

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

Inner exception:

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

enter image description here

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

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

Accept: application/json

It will work

From the 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.

How to remove XmlFormatter:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...