title: wcf service returning derived type
body: <p>I have a following sample wcf service (using webHttpBinding):  </p>
  
  <pre><code>[ServiceContract]
  public class Animals {
  
      [OperationContract]
      [WebGet(UriTemplate = "/{id}")]
      [ServiceKnownType(typeof(Dog))]
      public Animal GetAnimalById(string id) {
          switch (id) {
              case "1": return new Animal { Id = 1 };
              case "2": return new Dog { Id = 2 };
          }
          throw new ArgumentException();
      }
  }
  </code></pre>
  
  <p>Types are defined as follows:</p>
  
  <pre><code>[DataContract]
  [KnownType(typeof(Dog))]
  public class Animal {
      [DataMember]
      public int Id { get; set; } 
  }
  
  public class Dog : Animal {
      [DataMember]
      public string Name { get; set; }
  }
  </code></pre>
  
  <p>When 1 is supplied, the xml retured from the service is (xmlns omitted for brevity):</p>
  
  <pre><code>&lt;Animal&gt;&lt;Id&gt;1&lt;/Id&gt;&lt;Name i:nil="true"/&gt;&lt;/Animal&gt;
  </code></pre>
  
  <p>When 2 is supplied:  </p>
  
  <pre><code>&lt;Dog&gt;&lt;Id&gt;2&lt;/Id&gt;&lt;Name i:nil="true"/&gt;&lt;/Dog&gt;
  </code></pre>
  
  <p>And here is the question: <strong>Why can't DataContractSerializer constructed for Animal deserialize second xml?</strong> It throws something like: Expecting element 'Animal' from namespace 'bla bla'.. Encountered 'Element'  with name 'Dog', namespace 'bla bla'.</p>
  
  <p>Additional information:<br>
   1. If I construct DataContractSerializer supplying typeof(Dog) as parameter it obviously work.<br>
   2. If I construct DataContractSerializer supplying typeof(Animal) as parameter (cause I don't know the type of object I'm about to serialize / deserialize) and then serialize Dog the xml will look like this:  </p>
  
  <pre><code>&lt;Animal i:type="Dog"&gt;&lt;Id&gt;0&lt;/Id&gt;&lt;Name i:nil="true"/&gt;&lt;/Animal&gt;
  </code></pre>
  
  <p>Which can in turn be deserialized using same serializer without any problem. Can I force WCF to serialize using DataContractSerializer supplied with base type rather than derived (which seems more reasonable and probably should be there by default anyway)?</p>