prevent property from being serialized in web API prevent property from being serialized in web API asp.net asp.net

prevent property from being serialized in web API


ASP.NET Web API uses Json.Net as default formatter, so if your application just only uses JSON as data format, you can use [JsonIgnore] to ignore property for serialization:

public class Foo{    public int Id { get; set; }    public string Name { get; set; }    [JsonIgnore]    public List<Something> Somethings { get; set; }}

But, this way does not support XML format. So, in case your application has to support XML format more (or only support XML), instead of using Json.Net, you should use [DataContract] which supports both JSON and XML:

[DataContract]public class Foo{    [DataMember]    public int Id { get; set; }    [DataMember]    public string Name { get; set; }    //Ignore by default    public List<Something> Somethings { get; set; }}

For more understanding, you can read the official article.


According to the Web API documentation page JSON and XML Serialization in ASP.NET Web API to explicitly prevent serialization on a property you can either use [JsonIgnore] for the Json serializer or [IgnoreDataMember] for the default XML serializer.

However in testing I have noticed that [IgnoreDataMember] prevents serialization for both XML and Json requests, so I would recommend using that rather than decorating a property with multiple attributes.


Instead of letting everything get serialized by default, you can take the "opt-in" approach. In this scenario, only the properties you specify are allowed to be serialized. You do this with the DataContractAttribute and DataMemberAttribute, found in the System.Runtime.Serialization namespace.

The DataContactAttribute is applied to the class, and the DataMemberAttribute is applied to each member you want to be serialized:

[DataContract]public class MyClass {  [DataMember]  public int Id { get; set;} // Serialized  [DataMember]  public string Name { get; set; } // Serialized  public string DontExposeMe { get; set; } // Will not be serialized}

Dare I say this is a better approach because it forces you to make explicit decisions about what will or will not make it through serialization. It also allows your model classes to live in a project by themselves, without taking a dependency on JSON.net just because somewhere else you happen to be serializing them with JSON.net.