【问题标题】:WebAPI serializes classes that derive from abstract type properly when returning JSON, but not XMLWebAPI 在返回 JSON 而不是 XML 时正确序列化从抽象类型派生的类
【发布时间】: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


    【解决方案1】:

    您应该将KnownType 属性添加到Widget 类并指定可以作为BaseClass 实例Contents 列表传递的所有可能类型:

    [KnownType(typeof(ChildClass1))]
    [KnownType(typeof(ChildClass2))]
    public class Widget
    {        
        public List<BaseClass> Contents { get; set; }
        public Widget()
        {
            Contents = new List<BaseClass>();
        }
    }
    

    序列化响应:

    <Widget xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
            xmlns="http://schemas.datacontract.org/2004/07/YourNamespace">
        <Contents>
            <BaseClass i:type="ChildClass1">
                <id>1234</id>
                <shape>round</shape>
            </BaseClass>
            <BaseClass i:type="ChildClass2">
                <id>4321</id>
                <color>red</color>
            </BaseClass>
        </Contents>
    </Widget>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-12
      • 1970-01-01
      • 2014-12-13
      • 1970-01-01
      • 1970-01-01
      • 2020-08-26
      • 2017-03-22
      • 1970-01-01
      相关资源
      最近更新 更多