Web API OData V3 `$inlinecount` fails

后端 未结 2 1915
别那么骄傲
别那么骄傲 2020-12-04 22:10

I am using the out of the box ValuesController in a ASP.NET Web API application

 public class ValuesController : ApiController
 {
     // GET api/values
             


        
相关标签:
2条回答
  • 2020-12-04 22:56

    In OData v4, $inlinecount=allpages has been replaced by $count=true.

    $count just works with returning an IQueryable in the recent versions of aspnet mvc.

    0 讨论(0)
  • 2020-12-04 23:01

    Great question.

    $inlinecount out of the box only works when you're sending back OData responses. The reason for this is that OData defines special fields in the data that XML and JSON don't define. So in OData a response might look like this:

    {
      "odata.metadata":"http://localhost:12345/odata/$metadata#Customers",
      "odata.count":"4",
      "value":[ ... ]
    }
    

    Notice the wrapper with the "odata.count" property. This is different from the way the default XML and JSON formatters write out data because they don't have wrappers for this additional information. So other formatters are by default unchanged.

    Now you have several options:

    You could choose to use the OData format. For this, you'll want to follow the instructions in this blog post:

    http://blogs.msdn.com/b/webdev/archive/2013/01/29/getting-started-with-asp-net-webapi-odata-in-3-simple-steps.aspx

    You could also choose to instead return a PageResult<T>. This looks like this:

    public PageResult<Customer> Get(ODataQueryOptions<Customer> queryOptions)
    {
        IQueryable results = queryOptions.ApplyTo(_customers.AsQueryable());
        return new PageResult<Customer>(results as IEnumerable<Customer>, Request.GetNextPageLink(), Request.GetInlineCount());
    }
    

    This should work fine for OData, JSON, and XML by adding a wrapper object for XML and JSON that can include the Count and the next page link.

    0 讨论(0)
提交回复
热议问题