UNOWN301
UNOWN301

Reputation: 29

WCF Rest Method with abstract request type - Error: Cannot create an abstract class

In short, I have exposed a REST-ful endpoint for my WCF service like so:

<endpoint address="Rest" binding="webHttpBinding" behaviorConfiguration="web" contract="ServicesLayer.ServiceContract.IService" name="service-web" />

And I've added the WebInvoke attribute to all methods on the service interface like so:

[WebInvoke]
[OperationContract]
Response GetStuff(RequestBase Request);

Everything works fine for methods which have a request type that is concrete. But for any method with an abstract request type such as the one above in which RequestBase is abstract, the following error is returned: Cannot create an abstract class.

How do I force this method to interpret the request as one of RequestBase's derived types when calling this RESTfully?

Note: I did try to remove 'abstract' keyword from the RequestBase class, yet it still gets interpreted as a RequestBase rather than one of its derived classes, so that didn't solve any issues really.

Thanks in advance.

Upvotes: 0

Views: 482

Answers (2)

sigurjonfv
sigurjonfv

Reputation: 11

For those wondering how this looks in JSON. In my case, I needed to add the schema string.

This example assumes that you have a BasePersonCriteria which is abstract, and PersonNameCriteria which inherits BasePersonCriteria. I also had an attribute [KnownType(typeof(PersonNameCriteria))] on BasePersonCriteria.

If this is your request and criteria:

[DataContract(Namespace = "http://schemas.stackoverflow.com/core/persons/2018/11/14/criterias")]
public class PersonNameCriteria : BasePersonCriteria
{
    [DataMember]
    public string Name { get; set; }
}

[DataContract(Namespace = "http://schemas.stackoverflow.com/core/persons/2018/11/14/criterias")]
[KnownType(typeof(PersonNameCriteria))]
public abstract class BaseAccountCriteria
{
}

[DataContract(Namespace = "http://schemas.stackoverflow.com/core/persons/2018/11/14/requests")]
public class GetPersonRequest
{
    [DataMember(IsRequired = true)]
    public BasePersonCriteria PersonCriteria { get; set; }
}

This is how the JSON should look:

{
    "PersonCriteria": {
        "__type": "PersonNameCriteria:http://schemas.stackoverflow.com/core/persons/2018/11/14/criterias",
        "Name": "John"
    }
}

Upvotes: 1

UNOWN301
UNOWN301

Reputation: 29

Turns out I just needed to include the type in the json/xml request being sent. Once I added that it new which type to interpret it as. Thanks

Upvotes: 0

Related Questions