MVC WEB API List<string>返回自定义的XML节点名称
背景:
我们在API的返回对象中有一个List<string>属性的时候,MVC WEB API 默认返回的XML节点名称并不是我们想要的:
对象定义:
public class Answer : ModelBase { private List<string> _otherAnswer; public List<string> OtherAnswer { get { return _otherAnswer; } set { _otherAnswer = value; } } }
返回结果:
<Answer xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/RainbowWebApi.Models">
<Result>1</Result><ResultDedail>sucess</ResultDedail>
<MasterAnswer></MasterAnswer>
<MasterQuestion>九阴真经是什么?</MasterQuestion>
<OtherAnswer xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<d2p1:string>问题?</d2p1:string>
<d2p1:string>1</d2p1:string>
<d2p1:string>2?</d2p1:string>
<d2p1:string>3?</d2p1:string>
<d2p1:string>4?</d2p1:string>
</OtherAnswer>
<UserLogGuid>EE9175E2-DD93-8B48-AEE1-448248A2CCDF</UserLogGuid>
</Answer>
可以看到,OtherAnswer的下面节点为d2p1:string
解决:
1.在Golbal.asax.cs Application_Start()中设置XML序列化属性:
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true; }
2.实体类标识XML序列化的字段特性 XMLArrayItem,
public class Answer : ModelBase { private List<string> _otherAnswer; [XmlArrayItem("Question")] public List<string> OtherAnswer { get { return _otherAnswer; } set { _otherAnswer = value; } } }
3.下面就是我们想要的XML结果:
<Answer xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/RainbowWebApi.Models"> <Result>1</Result><ResultDedail>sucess</ResultDedail> <MasterAnswer></MasterAnswer> <MasterQuestion>九阴真经是什么?</MasterQuestion> <OtherAnswer xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays"> <Question>问题?<Question> <Question>1</Question> <Question>2?</Question> <Question>3?</Question> <Question>4?</Question> </OtherAnswer> <UserLogGuid>EE9175E2-DD93-8B48-AEE1-448248A2CCDF</UserLogGuid> </Answer>