如何在WebAPI中返回IEnumerable <int>(手动应用过滤器)</int>

时间:2013-03-09 12:46:59

标签: asp.net-mvc-4 .net-4.0 asp.net-web-api odata

我想返回我的进程的所有ID(Processo类)(之前应用过滤器和顺序),如下所示:

网址:api/processos/getIds?&$filter=(Id eq 1)

public IEnumerable<int> getIds(ODataQueryOptions opts)
{
    var results = Repositorio.Query<Processo>();

    results = opts.ApplyTo(results) as IQueryable<Processo>;

    return results.Select(p => p.Id).ToArray();
}

错误

WebApi primitive array error

  

完整图片位于:http://i.stack.imgur.com/gzJ7n.jpg


异常

System.ArgumentException was unhandled by user code
  HResult=-2147024809
  Message=Cannot apply ODataQueryOptions of 'System.Int32' to IQueryable of 'CreditoImobiliarioBB.Model.Processo'.
Parameter name: query
  Source=System.Web.Http.OData
  ParamName=query
  StackTrace:
       at System.Web.Http.OData.Query.ODataQueryOptions`1.ValidateQuery(IQueryable query)
       at System.Web.Http.OData.Query.ODataQueryOptions`1.ApplyTo(IQueryable query)
       at CreditoImobiliarioBB.Web.Api.processosController.getIds(ODataQueryOptions opts) in w:\Clients\creditoimobiliariobb.com.br\src\CreditoImobiliarioBB\CreditoImobiliarioBB.Web\Api\processosController.cs:line 39
       at lambda_method(Closure , Object , Object[] )
       at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass13.<GetExecutor>b__c(Object instance, Object[] methodParameters)
       at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
       at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.<>c__DisplayClass5.<ExecuteAsync>b__4()
       at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)
  InnerException: 

1 个答案:

答案 0 :(得分:2)

您需要为ODataQueryOptions提供类型参数,否则它将使用操作的返回类型来构建选项。这是固定代码:

public IEnumerable<int> getIds(ODataQueryOptions<Processo> opts)
{
    var results = Repositorio.Query<Processo>();

    results = opts.ApplyTo(results) as IQueryable<Processo>;

    return results.Select(p => p.Id).ToArray();
}