3

Say I have:

public class Parent{
    [ApiMember(Name = "parentItem")]
    public string Item {get; set;}
}

and

public class Child : Parent {
    [ApiMember(Name = "childItem")]
    public new string Item {get; set;}
}

Since the 'Item' property in the parent class should be hidden, why does making a request with {"childItem": "something"} returns Could not find property childItem on RequestObject? That said, what is the best way (or is there a way) to rename inherited API members/properties in the subclass?

natasha
  • 263
  • 1
  • 9

2 Answers2

3

[DataContract] and [DataMember] attributes affect serialization where as [Api*] attributes are only used to document and add extra metadata about your API, but it doesn't affect serialization behavior.

So you should instead change your DTOs to:

[DataContract]
public class Parent
{
    [DataMember(Name = "parentItem")]
    public virtual string Item { get; set; }
}

[DataContract]
public class Child : Parent 
{
    [DataMember(Name = "childItem")]
    public override string Item { get; set; }
}

Where they will be used when serializing in most of ServiceStack's serializers, e.g:

var json1 = new Parent { Item = "parent" }.ToJson();
json1.Print();

var json2 = new Child { Item = "child" }.ToJson();
json2.Print();

Which outputs:

{"parentItem":"parent"}
{"childItem":"child"}

You can try this example Live on Gistlyn.

mythz
  • 141,670
  • 29
  • 246
  • 390
1

Try making the property virtual in the parent and then simply override it (without new keyword) in the child class like that:

public class Parent{
    [ApiMember(Name = "parentItem")]
    public virtual string Item {get; set;}
}

public class Child : Parent {
    [ApiMember(Name = "childItem")]
    public override string Item {get; set;}
}
Szab
  • 1,263
  • 8
  • 18
  • I tried to do `public override string Item {get; set;} = "test default"` and I can see that the property is properly overriden as when I debug it, I can see the default value "test default". However, making a request with `{"childItem": "something"}` still returns `Could not find property childItem on RequestObject`. – natasha Oct 30 '18 at 01:03
  • Please post more code, e.g. a controller that's supposed to handle the request. – Szab Oct 30 '18 at 07:31