user437899
user437899

Reputation: 9269

ASP.NET Web API: XMLFormatter thinks he can write Json-objects

i have a method like this:

public JObject Get(int id)
        {
            return new JObject(new JProperty("Test", "Test"));
        }

It works fine if I request JSON, but if I request XML i get an HTTP-Errorcode 500 from the web api framework (no exception). It seems likely that the XMLformatter thinks he can write json. I can test it with:

bool test = GlobalConfiguration.Configuration.Formatters.XmlFormatter.CanWriteType(typeof(JArray));
            bool test2 = GlobalConfiguration.Configuration.Formatters.XmlFormatter.CanWriteType(typeof(JObject));
            bool test3 = GlobalConfiguration.Configuration.Formatters.XmlFormatter.CanWriteType(typeof(JProperty));
            bool test4 = GlobalConfiguration.Configuration.Formatters.XmlFormatter.CanWriteType(typeof(JValue));

It always returns "true". I dont want to remove the xmlformatter, but it is not acceptable that the server throws an HTTP Error 500 which I dont produce and cant solve. The best would be that the XMLformatter can serialize the object...

Upvotes: 2

Views: 994

Answers (2)

Filip W
Filip W

Reputation: 27187

DataContractSerializer does not support anonymous/dynamic types (or even generic "object"). That's why it's not getting serialized to XML.

If you want XML serialization, you have to use strongly typed objects.

Upvotes: 6

Darin Dimitrov
Darin Dimitrov

Reputation: 1039328

Why are you returning a JObject from your Web API method? That's JSON specific object which is not XML serializable. You should not return format specific objects,

just plain model objects (or HttpResponseMessage):

public object Get(int id)
{
    return new { Test = "Test" };
}

or strongly typed objects directly:

public class MyModel
{
    public string Test { get; set; }
}

and then:

public MyModel Get(int id)
{
    return new MyModel { Test = "Test" };
}

and leave the configured media formatters do the job of serializing this object to the proper format as requested by the client. Don't use any serialization format specific objects in your API actions. That's not their responsibility.

Upvotes: 1

Related Questions