Asp.net web api ASP.NET Web API IQueryable<;T>;挑战
我想在控制器中使用以下模式: api/{controller}/{id}/{collection} 示例:api/customers/123/地址 但是我想从相应的Get操作返回T的Asp.net web api ASP.NET Web API IQueryable<;T>;挑战,asp.net-web-api,Asp.net Web Api,我想在控制器中使用以下模式: api/{controller}/{id}/{collection} 示例:api/customers/123/地址 但是我想从相应的Get操作返回T的IQueryable。我想要这样的东西(简化): public IQueryable GetCollection(int-id,string-collection) { 开关(收集) { 案例“地址”: 返回_addresses.AsQueryable(); 打破 案例“订单”: 返回_orders.AsQu
IQueryable。我想要这样的东西(简化):
public IQueryable GetCollection(int-id,string-collection)
{
开关(收集)
{
案例“地址”:
返回_addresses.AsQueryable();
打破
案例“订单”:
返回_orders.AsQueryable();
打破
违约:
抛出新异常(不受支持);
}
}
可以这样做吗?
建议的方法是什么 只需返回非泛型IQueryable
或者通过协方差IQueryable
。@SLacks是正确的,如果可以,您应该返回IQueryable
或IQueryable
获取的错误是DataContract序列化程序的一个函数。所以你有几个选择
切换到支持所需内容的备用xml serlializer李>
Swtitch转换为绕过有问题的序列化程序的输出形式(例如使用JSON.net的JSON)
教数据协定序列化程序如何使用
对于“教学”选项,您可以通过两种方式进行教学
(A)利用[KnownType(typeof(…)])]
属性。给你。这是WCF的,但应该让你开始
(B)使用数据协定解析器。这个 扩展@Ebarr所说的内容,实现这一点的最简单方法是更新您希望能够以这种方式返回的各种类,并让它们从公共基类或接口继承
例如:
[KnownType(typeof(Address))]
[KnownType(typeof(Order))]
public abstract class _BaseObject { }
public partial class Address : _BaseObject { }
public partial class Order : _BaseObject { }
现在,您可以使控制器方法如下所示:
public IQueryable<_BaseObject> GetCollection(int id, string collection) {
switch(collection) {
case "addresses":
return _addresses.AsQueryable();
case "orders":
return _orders.AsQueryable();
default:
throw new NotSupportedException();
}
}
public IQueryable GetCollection(int-id,string-collection){
开关(集合){
案例“地址”:
返回_addresses.AsQueryable();
案例“订单”:
返回_orders.AsQueryable();
违约:
抛出新的NotSupportedException();
}
}
请注意,[KnownType]
属性位于System.Runtime.Serialization
中。您还应该知道,此方法将产生与JSON
序列化完全相同的结果-但是XML
序列化通常会产生将对象显示为基类(因为这是您返回的)而不是子类的标记。这两个建议都失败,恐怕。我在这两种情况下都会遇到异常。1)IQueryable提供:System.Runtime.Serialization.SerializationException:Type'System.Linq.EnumerableQuery'1[[MVCAPApplication1.Controllers.Address,MVCAPApplication1,Version=1.0.0,Culture=neutral,PublicKeyToken=null]],数据协定名为“ArrayOfadAddress:”。考虑使用DATACONTRORTCORDEVER或将未知类型的任何类型添加到已知类型的列表中,例如,通过使用KnownTypeAttribute属性或将它们添加到传递给DataContractSerializer的已知类型列表中。2)IQueryable给出:System.Xml.XmlException:在使用本地名称“\uu type”写入属性后,必须写入属性“type”=“object”。
public IQueryable<_BaseObject> GetCollection(int id, string collection) {
switch(collection) {
case "addresses":
return _addresses.AsQueryable();
case "orders":
return _orders.AsQueryable();
default:
throw new NotSupportedException();
}
}