Using WCF with abstract classes

2020-05-19 05:50发布

How do I define DataContract for abstract classes in WCF?

I have a class "Person" which I communicate successfully using WCF. Now I add a new class "Foo" referenced from Person. All still good. But when I make Foo abstract and define a sub class instead it fails. It fails on the server side with a CommunicationException, but that doesn't really tell me much.

My simplified classes made for testing:

[DataContract]
public class Person
{
    public Person()
    {
        SomeFoo = new Bar { Id = 7, BaseText = "base", SubText = "sub" };
    }

    [DataMember]
    public int Id { get; set; }

    [DataMember]
    public Foo SomeFoo { get; set; }
}

[DataContract]
public abstract class Foo
{
    [DataMember]
    public int Id { get; set; }

    [DataMember]
    public string BaseText { get; set; }
}

[DataContract]
public class Bar : Foo
{
    [DataMember]
    public string SubText { get; set; }
}

2条回答
Rolldiameter
2楼-- · 2020-05-19 06:01

Interesting.

I would expect that code to fail in the Person constructor since you can't directly instantiate an Abstract Class.

查看更多
相关推荐>>
3楼-- · 2020-05-19 06:03

I figured it out. You need to specify the subclasses on the abstract base class using "KnownType". The solution would be to add this on the Foo class:

[DataContract]
[KnownType(typeof(Bar))] // <------ added
public abstract class Foo
{
    [DataMember]
    public int Id { get; set; }

    [DataMember]
    public string BaseText { get; set; }
}

Check out this link.

查看更多
登录 后发表回答