Exclude property on WCF DataContract

我是研究僧i 提交于 2020-01-22 03:33:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!