d.997
d.997

Reputation: 73

Hiding derived class in WCF

I want to hide derived class from the client in my WCF service.

Example -

[DataContract]
public class Base
{
    public int Id {get; set;}
}

public class Derived : Base
{         
    public string Name {get; set;}
}

Let's say I've operational contract like

[OperationalContract]
Base GetData();

Implementation of operational contract

public Base GetData()
{
    Derived = new Derived {Id = 1, Name = "Foo" };
    return derived;
}

The above example doesn't work. If I add [KnownType(typeof(Derived)] in Base class, and add DataContract attribute to Dervied class then everything seems to work fine. But if I do that the client will see the Derived class, that I want to hide. Is it possible to hide Derived class from the client? Thanks

Upvotes: 1

Views: 867

Answers (1)

Val Akkapeddi
Val Akkapeddi

Reputation: 1183

I think you'll get the behavior you want hacking equivalence using named DataContracts instead of adding the KnownType attribute, like so:

[DataContract(Name="Reply")]
public class Base
{
    [DataMember]
    public virtual int IntValue { get; set; }

}

[DataContract(Name = "Reply")]
public class Derived : Base
{

    public String StringProperty { get; set; }
}



Derived blah = new Derived { IntValue = 3, StringProperty = "blah" };
public Base SomeOperation()
{
     return blah;
}

Does this do what you want? Also have a look at DataContractSurrogates (http://blogs.msdn.com/b/carlosfigueira/archive/2011/09/14/wcf-extensibility-serialization-surrogates.aspx), which is all told a fancy way for WCF to support what zimdanen said - creating a type for your API, and converting your internal type into this API type in a less "hacky" way.

Upvotes: 2

Related Questions