Muhammad Kazim Muhammad Kazim - 4 months ago 12
ASP.NET (C#) Question

ASP.Net Web API Xml searlization issue

We are facing multiple issues with xml searilization of ASP.NET WebAPI. Currently we are using

xmlserializer
instead of
DataContractSearilizer
(which is a default serialization method for XML serialization) for two basic reasons.


  1. In
    DataContractSearlizer
    We need to pass all the fields of object in ascending order otherwise getting null at api end.

  2. We also need to pass namespace in XML header for passing XML object to web api.



For these two basic reasons we decided to go for
xmlserializer
instead of
DataContractSearlizer
. But now we are facing another issue which was not present in default
DataContractSearilization
mechanism. Let say we have an object like this

[DataContract]
public class Car
{
public int ID;

[DataMember]
public string CarName;

[DataMember]
public string CarType;

}


Now we were expecting that on client end we will only receive the those fields surrounded by DataMember attribute but unexpectedly we are getting all the fields whether DataMember attribute present or absent. This is perfectly working fine in json searlization and result was what we were initially expected. Can someone help us in this regard?

Answer

You are probably looking for the IgnoreDataMember Attribute:

When applied to the member of a type, specifies that the member is not part of a data contract and is not serialized.

[DataContract]
public class Car
{
    [IgnoreDataMember]
    public int ID;

    [DataMember]
    public string CarName;

    [DataMember]
    public string CarType;

}
Comments