Search code examples
wcfserializationdatacontract

Role base dataContract


Just giving an example. I have a WCF service with a method that returns a datacontract. Data contract has several data members, and service is being used by several clients. few members in data contract has sensitive info which should not go to all the clients. What is the best way to control the data flow from wcf to client. If such data members show default values, thats fine with me. I want to avoid code of each type of client and want to use some configuration approach. Like, in a config file, I can write all the property to be serialized as comma separated string. For those not serialized, can I pass "Not authorized" exception to the client when client try to access the property. Why I am asking to avoid code is, each data member could be itself counted for subscription cost. The there could be lots of contracts, and expanding.


Solution

  • Dynamic contracts are not possible with WCF. What you can do is have a base data contract class, and then inherit from that:

    [DataContract]
    public class MyOperationResultBase { ... }
    
    
    [DataContract]
    public class SpecificSchema01 : MyOperationResultBase { ... }
    

    and then in your service you can do

    [OperationContract]
    public MyOperationResultBase DoMyOperation(MyOperationRequest request) { ... }
    

    Then you return an instance of the applicable derived class as needed.

    Obviously this also means that your client must check the type of the returned result, and you must specify the types of the derived classes in your base class (or create a type resolver, but you can do that later if this solution is proven to work for you) :

    [KnownType(typeof(SpecificSchema01))]
    [KnownType(typeof(SpecificSchema02))]
    [KnownType(typeof(SpecificSchema03))]
    [DataContract]
    public class MyOperationResultBase { ... }
    

    Is this what you are looking for?