【发布时间】:2017-02-04 01:00:48
【问题描述】:
我的模特:
public abstract class BaseClass
{
public string id { get; set; }
}
[KnownType(typeof(BaseClass))]
public class ChildClass1 : BaseClass
{
public string shape { get; set; }
}
[KnownType(typeof(BaseClass))]
public class ChildClass2: BaseClass
{
public string color { get; set; }
}
public class Widget
{
public List<BaseClass> Contents { get; set; }
public Widget()
{
Contents = new List<BaseClass>();
}
}
我的网络 api 端点:
[HttpGet]
public Widget Get()
{
Widget widget = new Widget();
ChildClass1 cc1 = new ChildClass1();
cc1.id = "1234";
cc1.shape = "round";
ChildClass2 cc2 = new ChildClass2();
cc2.id = "4321";
cc2.color = "red";
widget.Contents.Add(cc1);
widget.Contents.Add(cc2);
return widget;
}
当请求输出为 XML 时,序列化我的派生类时遇到问题。
“ObjectContent`1”类型未能序列化响应正文 内容类型'应用程序/xml; charset=utf-8'。
使用数据合同名称键入“WebApplication1.Models.ChildClass1” 'ChildClass1:http://schemas.datacontract.org/2004/07/WebApplication1.Models' 预计不会。如果您是,请考虑使用 DataContractResolver 使用 DataContractSerializer 或添加任何静态未知的类型 已知类型的列表 - 例如,通过使用 KnownTypeAttribute 属性或通过将它们添加到传递给 序列化器。
【问题讨论】:
标签: c# asp.net-web-api asp.net-web-api2