Using the apicontroller to return odata.$count

梦想与她 提交于 2019-12-24 03:12:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!