【问题标题】:HTTP Get return multiple typesHTTP Get 返回多种类型
【发布时间】:2014-06-16 13:53:49
【问题描述】:

我正在编写一个 Web 服务,并尝试添加对 Get 请求的响应。困难是,我有多种类型需要返回。所以最初我有一个基类:

public abstract class AbstractSource
{
    public string name { get; set; }
}

后跟两个导数:

public class DatabaseSource : AbstractSource
{
}

public class WebSource : AbstractSource
{

}

这些类最终会有更多自己的特定元素。在我的控制器类中,我有以下测试代码:

public class DataSourcesController : ApiController
{
    AbstractSource[] sources = new AbstractSource[] 
    { 
        new WebSource { name="WebPath"},
        new DatabaseSource{name="DB Source"}
    };

    public IEnumerable<AbstractSource> GetAllDataSources()
    {
        return sources;
    }
}

现在,当我运行它时,我得到了一个序列化异常。甚至可以像这样返回多种类型吗?

【问题讨论】:

  • 你能分享你的序列化异常吗?你用的是什么序列化器?您如何期望客户端“找到”正确的类型以绑定回?

标签: c# web-services rest asp.net-web-api get


【解决方案1】:

听起来您正在尝试使用 XML 格式获取数据。

XML 序列化程序(例如DataContractSerializer)不知道如何将AbstractSource 反序列化为DatabaseSourceWebSource,因此您需要捕捉[KnownType(...)] 上的[KnownType(...)] 属性AbstractSource类:

using System.Runtime.Serialization;

[KnownType(typeof(DatabaseSource))]
[KnownType(typeof(WebSource))]
public abstract class AbstractSource
{
    public string name { get; set; }
}

【讨论】:

  • 我认为它是这样的,但已经走上了使用 [XmlInclude] 而不是 [KnownType] 的道路。谢谢!
猜你喜欢
  • 2016-09-09
  • 2021-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多