This project is read-only.

Class inheritance in XmlMediaTypeFormatter

Topics: ASP.NET Web API
Nov 20, 2012 at 6:39 PM

The behavior for the SetSerializer method is not correct for some cases where support for class inheritance is required. If I have the following class hierarchy,


public class Base

public class B : Base

I would like to create a new instance of DataContractSerializer and set B as a well-know type for Base using code (Not decorating the Base class with attributes). 

 var mySerializer = new DataContractSerializer(typeof(Base), new Type [] { typeof(B) });


The code above does not work as expected, as my Web API controller method is returning an instance of B, and the formatter is looking for a serializer for B and not Base where the well-know types were defined.

A similar scenario is presented when a custom resolver must be used with the data contract serializer.

Nov 28, 2012 at 8:16 PM

Hi Pablo,

This is by design. The SetSerializer method works on the declared type of the action and needs to match exactly. Inheritance doesn't apply. Is there any reason you can't just change the declared type on your action to Base?

We're looking into adding more extensibility to the XmlMediaTypeFormatter so that you can create the right serializer for your type at runtime for a future release. That would allow you to customize the serializer in a more fine-grained way than by using SetSerializer.