asp.net web api KnownTypeAttribute

项目里用到了继承,在序列化的时候遇到了问题。

源代码

    public class Segment
    {
        public SegmentType Type { get; set; }
        public string Text { get; set; }
    }

    public class SegmentUrl : Segment
    {
        public string Url { get; set; }
    }

    [JsonConverter(typeof(StringEnumConverter))]
    public enum SegmentType
    {
        Text,
        Link
    }

使用的时候是以 Segment 对象来存储 SegmentUrl 对象的,JSON格式序列化的时候正常。

[
    {
        "Type": "Text",
        "Text": "test   哈哈哈哈"
    },
    {
        "Url": "http://home.cnblogs.com/ing/647524/",
        "Type": "Link",
        "Text": "home.cnblogs.com..."
    }
]

但是在格式化的时候却报错了。

“ObjectContent`1”类型未能序列化内容类型“application/xml; charset=utf-8”的响应正文。
不应为数据协定名称为“SegmentUrl:http://schemas.datacontract.org/2004/07/IngService.Models”的类型“***.Models.SegmentUrl”。请考虑使用 DataContractResolver,或将任何未知类型以静态方式添加到已知类型的列表。例如,可以使用 KnownTypeAttribute 特性,或者将未知类型添加到传递给 DataContractSerializer 的已知类型列表。

然后百度:http://www.cnblogs.com/zlgcool/archive/2008/12/20/1359031.html 发现引用不到该属性,找不到该类。然后求助谷歌,同样也是这个解决方案,最后发现要引用System.Runtime.Serialization程序集才行,又犯了低级错误,蛋疼啊卧槽,,,,,

xml序列化后结果是这样的 多了一个 i:type="SegmentUrl" 字样

<?xml version="1.0" encoding="utf-8"?>

<ArrayOfIngComment xmlns="http://schemas.datacontract.org/2004/07/***.Models" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">  
  <Segment> 
    <Text>test 哈哈哈哈</Text>  
    <Type>Text</Type> 
  </Segment>  
  <Segment i:type="SegmentUrl"> 
    <Text>home.cnblogs.com...</Text>  
    <Type>Link</Type>  
    <Url>http://home.cnblogs.com/ing/647524/</Url> 
  </Segment> 
</ArrayOfIngComment>

http://stackoverflow.com/questions/12936713/web-api-error-the-objectcontent1-type-failed-to-serialize-the-response-body

原文地址:https://www.cnblogs.com/grj1046/p/4338414.html