ASP.NET Web API:XMLFormatter认为他可以编写Json对象

use*_*899 2 xml json asp.net-mvc-4 asp.net-web-api

我有这样的方法:

public JObject Get(int id)
        {
            return new JObject(new JProperty("Test", "Test"));
        }
Run Code Online (Sandbox Code Playgroud)

如果我请求JSON,它工作正常,但如果我请求XML,我从web api框架获得HTTP-Errorcode 500(没有例外).XMLformatter似乎认为他可以编写json.我可以测试它:

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));
Run Code Online (Sandbox Code Playgroud)

它总是返回"true".我不想删除xmlformatter,但服务器抛出HTTP错误500是不可接受的,我不会生成并且无法解决.最好的是XMLformatter可以序列化对象......

Fil*_*p W 6

DataContractSerializer不支持匿名/动态类型(甚至是通用"对象").这就是为什么它没有被序列化为XML.

如果需要XML序列化,则必须使用强类型对象.