XmlSerializer 忽略 WebApi 中的 [XmlAttribute] [英] XmlSerializer ignores [XmlAttribute] in WebApi
问题描述
我有一个返回一个简单对象的 WebApi,但是当我强制它返回为 XML (Accept: application/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; }
}
我在代码中是这样返回的:
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 是:
<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 忽略 WebApi 中的 [XmlAttribute]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!