问题描述
我正在使用WEB API返回对象(类).
I am using WEB API to return an object (class).
类已经使用System.Xml.Serialization属性进行结构化,这使得使用WEB API很难返回整个类,因为它公开了更多信息.我认为序列化类并返回字符串不是解决方案,所以我想返回可序列化的对象.
Class is already being structured using System.Xml.Serialization attributes, which makes if difficult to return entire class using WEB API, since it exposes more then it should. I don't think it is a solution to serialize class and return a string, so I want to return a serializable object.
这是我班上的一个简短例子
Here is a short example of my class
[XmlIgnore]
[System.Xml.Serialization.XmlAttributeAttribute()]
public SettingEnums.currencyCodesEnum currency
{
get;
set;
}
[XmlAttributeAttribute("currency")]
public string Serializablecurrency
{
get { return this.currency.ToString(); }
set { }
}
如何返回遵循此类中定义的序列化属性的可序列化对象?
How can I return serializable object that follows serialization attributes defined in this class?
推荐答案
ASP.NET Web API确实使用了在类级别定义的序列化属性.但是,默认情况下, XmlMediaTypeFormatter
使用 DataContractSerializer
.由于您使用的是 XmlSerializer
,因此需要告诉Web API使用相同的代码.
ASP.NET Web API does use the serialization attributes defined at the class level. However, XmlMediaTypeFormatter
uses DataContractSerializer
by default. Since you are using XmlSerializer
, you need to tell Web API to use the same, like this.
GlobalConfiguration.Configuration.Formatters
.XmlFormatter.UseXmlSerializer = true;
这篇关于WEB API返回序列化属性后的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!