Derived type's properties missing in JSON response from ASP.NET Core API

前端 未结 6 1854
无人共我
无人共我 2021-02-13 02:51

The JSON response from my ASP.NET Core 3.1 API controller is missing properties. This happens when a property uses a derived type; any properties defined in the derived type but

6条回答
  •  借酒劲吻你
    2021-02-13 03:01

    This is the expected result. You're upcasting when you do that, so what will be serialized is the upcasted object, not the actual derived type. If you need stuff from the derived type, then that has to be the type of the property. You may want to use generics for this reason. In other words:

    public class Result
        where TResultProperty : IResultProperty
    {
        public TResultProperty ResultProperty { get; set; }   // property uses an interface type
    }
    

    Then:

    return new Result {
        ResultProperty = new StringResultProperty { Value = "Hi there!" }  
    };
    

提交回复
热议问题