Tuesday 2 February 2016

WCF Known Types

WCF allows you to write web service methods that take or return objects of multiple types using the KnownType attribute. This is done by defining a base class and inheriting from this class for other classes that you want to use as parameters. The base type is decorated with the KnownType attribute for each inherited type and you use the base type as the parameter on your web service method.

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.


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):
$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:#MyNameSpace
After 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});