.NET WebAPI 序列化 k_BackingField 脏 [英] .NET WebAPI Serialization k_BackingField Nastiness
问题描述
当我序列化以下内容时:
When i serialize the following:
[Serializable]
public class Error
{
public string Status { get; set; }
public string Message { get; set; }
public string ErrorReferenceCode { get; set; }
public List<FriendlyError> Errors { get; set; }
}
我得到了这令人作呕的烂摊子:
I get this disgusting mess:
<ErrorRootOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Printmee.Api">
<_x003C_Errors_x003E_k__BackingField>
An exception has occurred. Please contact printmee support
</_x003C_Errors_x003E_k__BackingField>
<_x003C_LookupCode_x003E_k__BackingField>988232ec-6bc9-48f3-8116-7ff7c71302dd</_x003C_LookupCode_x003E_k__BackingField>
</ErrorRootOfstring>
什么给?我怎样才能让它漂亮?JSON 响应还包含 k_BackingField
What gives? How can i make this pretty? JSON responses also contain the k_BackingField
推荐答案
默认情况下你不需要使用 [Serializable]
和 [DataContract]
来工作使用 Web API.
By default you don't need to use neither [Serializable]
nor [DataContract]
to work with Web API.
让您的模型保持原样,Web API 会为您序列化所有公共属性.
Just leave your model as is, and Web API would serialize all the public properties for you.
只有当您想对包含的内容有更多的控制时,您才可以使用 [DataContract]
和要包含在 [DataMember]
中的属性来装饰您的类(因为DCS 和 JSON.NET 都尊重这些属性).
Only if you want to have more control about what's included, you then decorate your class with [DataContract]
and the properties to be included with [DataMember]
(because both DCS and JSON.NET respsect these attributes).
如果由于某种原因,您的类需要 [Serializable]
(即您出于某种原因将其序列化为内存流,进行深度复制等),那么您必须同时使用两者属性结合以防止支持字段名称:
If for some reason, you need the [Serializable]
on your class (i.e. you are serializing it into a memory stream for some reason, doing deep copies etc), then you have to use both attributes in conjunction to prevent the backing field names:
[Serializable]
[DataContract]
public class Error
{
[DataMember]
public string Status { get; set; }
[DataMember]
public string Message { get; set; }
[DataMember]
public string ErrorReferenceCode { get; set; }
[DataMember]
public List<FriendlyError> Errors { get; set; }
}
这篇关于.NET WebAPI 序列化 k_BackingField 脏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!