.NET WebAPI Serialization k_BackingField Nastiness

By default you don’t need to use neither [Serializable] nor [DataContract] to work with Web API.

Just leave your model as is, and Web API would serialize all the public properties for you.

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).

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; }
}

Leave a Comment