问题
Given a WCF interface definition like this, is there a way to exclude a property from the ComplexObject response value?
I want to exclude the ChildObjects property. I don't want to remove the DataMember attribure from the property definition as I need it to be serialized in another case.
[ServiceContract]
public interface IComplexObjectService
{
[OperationContract]
ComplexObject Test(int a);
}
ComplexObject is defined something like this:
[DataContract(IsReference = true)]
public class ComplexObject
{
[DataMember]
public long ObjectCode
{
get { return _ObjectCode; }
set { _ObjectCode = value; }
}
[DataMember]
public List<ComplexObject> ChildObjects
{
get { return _ComplexObject; }
set { _ComplexObject = value; }
}
}
回答1:
You are going to have to remove the DataMember attribute if you don't want to expose the ChildObjects property in your ComplexObject. If you have another use case which requires the ChildObjects then I suggest you have a separate ComplextObject which does have it. You cannot just switch it on or off at run-time as it will violate the contract definition.
回答2:
[DataContract(IsReference = true)]
public class ComplexObject
{
public ComplexObject()
{
ChildObjects=null;
}
[DataMember]
public long ObjectCode
{
get { return _ObjectCode; }
set { _ObjectCode = value; }
}
[DataMember]
public List<ComplexObject> ChildObjects
{
get { return _ComplexObject; }
set { _ComplexObject = value; }
}
}
来源:https://stackoverflow.com/questions/15423405/exclude-property-on-wcf-datacontract