Dynamically ignore data members from getting serialized

前端 未结 4 1296
眼角桃花
眼角桃花 2020-12-19 01:48

We have an existing WCF service which uses several DataContracts. We want to modify the serialization based on the device, so that when accessed from mobile devices, the ser

4条回答
  •  清酒与你
    2020-12-19 02:16

    There is a approach, but I think this will require extra DataContract to be generated but still no need for separate operation and data contracts for different types of devices. It can classic implementation to run-time polymorphism. I am just giving idea:

    Say you have a generic DataContract like :

    [DataContract]
    [KnownType(typeof(Extra))]
    [KnownType(typeof(Extra2))]
    public class TokenMessage
    {
        string tokenValue;
        string extraValue;
        [DataMember]
        public string Token
        {
            get { return tokenValue; }
            set { tokenValue = value; }
        }
    
    }
    

    Other device specific contracts can inherit TokenMessage as base class like:

    [DataContract]
    public class Extra:TokenMessage
    {
      [DataMember]
      public string Extra 
      {
        get ;set;
      }
    }
    
    [DataContract]
    public class Extra2:TokenMessage
    {
      [DataMember]
      public string Extra2 
      {
        get ;set;
      }
    }
    

    Now at run-time as you say you know an argument in the operation contract, which helps us identify the device. Say based on device type, you can instantiate base class with derived class like:

    TokenMessage tm= new Extra();
    

    OR

    TokenMessage tm= new Extra2();
    

    So at run-time you will decide which device contract will be part of genric response.

    Note: Adding KnownType will generate the separate xsd within wsdl for all known types within base class, but saves serialization for data at run-time as this should depend on actual inheritance chosen.

提交回复
热议问题