问题
I have controllers that inherit from ApiController. I have the EnableQuery attribute at the top of it to allow ODATA query strings. However $count does not work.
For eg:- ../products?$count=true does return data with no odataexception, but does not return the count. Any suggestions
回答1:
You can get count separately and put it in new dictionary together with data, returning this dictionary in the method of your controller. The following code applies all that was specified in OData query (including select, expand and filter) and returns both data and count:
public class ProductsController : ApiController
{
public IHttpActionResult Get(ODataQueryOptions<Product> queryOptions)
{
IQueryable<Product> products = ... ///any IQueryable<Product>
var results = queryOptions.ApplyTo(products);
var dict = new Dictionary<string, object>();
if (Request.ODataProperties().TotalCount != null)
{
dict.Add("@odata.count", Request.ODataProperties().TotalCount);
}
dict.Add("value", results);
return Ok(dict);
}
}
However, to use ODATA in a way recommended by ASP.NET Web API documentation, you'll need to use ODataController instead of ApiController
来源:https://stackoverflow.com/questions/26523640/using-the-apicontroller-to-return-odata-count