WEB Bare format requires all known types to be declared on the service

This article has been archived. It is offered "as is" and will no longer be updated.
Symptoms

When you access a Web/WCF service, you may receive an error message that resembles the following:

The server encountered an error processing the request. Please see the service help page for constructing valid requests to the service. The exception message is 'Cannot serialize parameter of type 'MyService.MyDerivedClass' (for operation 'DoSomething', contract 'IMyContract') because it is not the exact type 'MyService.MyBaseClass' in the method signature and is not in the known types collection. In order to serialize the parameter, add the type to the known types collection for the operation using ServiceKnownTypeAttribute.'. See server logs for more details.

Cause

When an operation contract that should return a base class returns a derived class, then the contract is marked by the KnownType attribute or by the ServiceKnownType attribute.

The contract may resemble the following:

    [ServiceContract]
    interface IMyContract
    {
        [OperationContract]
        [WebGet]
        MyBaseClass DoSomething();
    }

    [DataContract]
    [KnownType(typeof(MyDerivedClass))]
    public class MyBaseClass
    {

    }

    [DataContract]
    public class MyDerivedClass : MyBaseClass
    {

    }

This contract would function correctly for WCF services that are not Web-based. These services do not use the WebHttpBinding class.  However, if the contract uses the WebHttpBinding class, the contract still functions incorrectly even though the KnownType attribute is set.

Resolution

To make the contract function correctly, the KnownTypeAttribute class must be set by using the ServiceKnownType attribute instead of the KnownType attribute. To do this, modify the code that is described in the "Cause" section to resemble the following code:

    [ServiceContract]
    interface IMyContract
    {
        [OperationContract]
        [WebGet,ServiceKnownType(typeof(MyDerivedClass))]
        MyBaseClass DoSomething();
    }

    [DataContract]
    public class MyBaseClass
    {

    }

    [DataContract]
    public class MyDerivedClass : MyBaseClass
    {

    }

Alternatively, the ServiceKnownType attribute can be placed on the service instead of on the operation.

Properties

Article ID: 2020469 - Last Review: 12/12/2015 07:16:16 - Revision: 1.0

Windows Communication Foundation

  • kbnosurvey kbarchive KB2020469
Feedback