Here's a quick example of a base class, derived class and using the KnownType attribute on the base class. It also includes a service contract with a web service method that accepts our base class.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace MyNameSpace | |
{ | |
[DataContract] | |
[KnownType(typeof(DerivedClass))] | |
public class BaseRequest | |
{ | |
[DataMember] | |
public int ID; | |
} | |
[DataContract] | |
public class DerivedClass : BaseRequest | |
{ | |
[DataMember] | |
public string FirstName; | |
} | |
[ServiceContract] | |
public interface IMyContract | |
{ | |
[OperationContract] | |
[WebInvoke(Method = "POST", UriTemplate = "/Items/{itemID}")] | |
public void UpdateItem(BaseRequest req, string itemID); | |
} | |
} |
When implementing the web service method, we can then check the type of the class we're being passed and react accordingly.
You can call this web service from your web front-end (here I'm using AngularJS):
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace MyNameSpace | |
{ | |
public class MyServices : WebService, IMyContract | |
{ | |
public void UpdateItem(BaseRequest req, string itemID) | |
{ | |
if (req is DerivedClass) | |
{ | |
// do something with derrived class | |
} | |
else | |
{ | |
// do something with base class | |
} | |
} | |
} | |
} |
You can call this web service from your web front-end (here I'm using AngularJS):
$http.post(urlBase + '/Items/' + id, {'req': data});To tell WCF which type you are passing to the web service method, you need to add a property to the object in the following format (that's two underscores):
__type: DerivedClass:#MyNameSpaceAfter a lot of experimentation, I could only see the object in the web service method as the base type. I finally got it working when I discovered that the __type property has to be the first property when the object is serialized to JSON. The following solves the problem by creating a new object in JavaScript with the __type property and then adds the properties from the original object:
var d = {__type: 'DerivedClass:#MyNameSpace'};for (var i in data) {d[i] = data[i];}$http.post(urlBase + '/Items/' + id, {'req': d});