How to apply paging specifically to a list which is part of a JSON using asp.net OData protocol

风格不统一 提交于 2020-01-25 01:21:09

问题


Below is a get method in my controller. It returns a JSON containing boolean "success', string "message" and a list. How can i query the list using OData? Generally if the return type was IQueryable then the following would work api/Category/all?$top=5 to get the top 5....But what should i do in my case?

// Get all Categories
    [HttpGet]
    [ActionName("all")]
    [Queryable]
    public HttpResponseMessage GetCategoryList()
    {          

        var categoryList = this.Repository.GetCategories().AsQueryable<Category>();

        return Request.CreateResponse(HttpStatusCode.OK, new ResponseMessage<IQueryable<Category>> { success = true, data = categoryList });

    }

public class ResponseMessage<T>  where T: class
{
    public string message;

    public bool success;

    public T data;
}

回答1:


With the details that you have provided, the solution just seems to be utilizing the odata format. What i mean by that is that an ODATA provider, that supports the query syntax you mention, is not utilized here. So, you'll have to handle the paging scenario yourself.

There is an upcoming library, Microsoft ASP.NET Web API OData 0.2.0-alpha, that would provide that functionality but it is still in alpha.

You can bind your query string to action parameters by naming the action parameters the same as query string id. So, by modifying the action as GetCategoryList(int top) you'll be able to get the value of the top parameter in the parameter. You'll have to handle the scenario for the next X also.




回答2:


You can use ODataQueryOptions<T> to solve the problem. Your code will look like:

[HttpGet]
[ActionName("all")]
public HttpResponseMessage GetCategoryList(ODataQueryOptions<Category> options)
{          

    var categoryList = this.Repository.GetCategories().AsQueryable<Category>();
    categoryList = options.ApplyTo(categoryList) as IQueryable<Category>;

    return Request.CreateResponse(HttpStatusCode.OK, new ResponseMessage<IQueryable<Category>> { success = true, data = categoryList });

}

ODataQueryOptions should work same as QueryableAttribute.



来源:https://stackoverflow.com/questions/13451649/how-to-apply-paging-specifically-to-a-list-which-is-part-of-a-json-using-asp-net

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