XmlSerializer的忽略[XmlAttribute]中的WebAPI [英] XmlSerializer ignores [XmlAttribute] in WebApi

查看:197
本文介绍了XmlSerializer的忽略[XmlAttribute]中的WebAPI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回一个简单对象的WebAPI,但是当我在迫使它返回的XML(接受:应用程序/ XML ),它忽略了 [XmlAttribute] 属性我已经在对象上设置。

I have a WebApi that returns a simple object, but when I'm forcing it to return as XML (Accept: application/xml) it ignores the [XmlAttribute] attribute I've set on the object.

这是我的对象:

public class Foo
{
    [XmlAttribute]
    public string Bar { get; set; }
}

和我在code返回它是这样的:

And I return it like this in the code:

[RoutePrefix("api/mytest")]
public class MyTestController : System.Web.Http.ApiController
{
    [HttpGet]
    [Route("gettest")]
    public Foo GetTest()
    {
        return new Foo() { Bar = "foobar" };
    }
}

生成的XML是:

The resulting XML is:

<Foo>
    <Bar>foobar</Bar>
</Foo>

而我希望它这样被退回:

Whereas I would expect it to be returned like this:

<Foo Bar="foobar">
</Foo>

为什么用的WebAPI使用XmlSerializer的忽略 [XmlAttribute] 属性,我怎样才能使它工作就像我想?

Why does the XmlSerializer used by WebApi ignore the [XmlAttribute] attribute, and how can I make it work like I want to?

推荐答案

尝试在你的WebAPI设置这个全局配置值设置为true

Try setting this global configuration value in your WebApi to true

GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;

在默认情况下的Web API中XmlMediaTypeFormatter使用的DataContractSerializer。

By default Web API uses DataContractSerializer in XmlMediaTypeFormatter.

这篇关于XmlSerializer的忽略[XmlAttribute]中的WebAPI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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