Web API 2 学习笔记 - 分页
Web API 2.2 odata v4 -系列的学习笔记,只共我个人参考。如果您不小心看了,发现有错误,请指正我,如果你是想学习,请离开哦 !
参考 : http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/supporting-odata-query-options (这个是v3哦)
不 response odata format 的做法是这样的
[Route("")] //[EnableQuery] <--不要放这个! public PageResult<Salesman> Get(ODataQueryOptions<Salesman> options) { //有set分页,才会有NextLink ODataQuerySettings settings = new ODataQuerySettings() { PageSize = 2 }; //因为没有[EnableQuery],所以这里我们要自己来valid一下 ODataValidationSettings vSettings = new ODataValidationSettings() { AllowedQueryOptions = AllowedQueryOptions.Count | AllowedQueryOptions.Filter //support count and filter only }; options.Validate(vSettings); //这里fail会 throw ODataException IQueryable results = options.ApplyTo(db.salesmans, settings); return new PageResult<Salesman>( results as IEnumerable<Salesman>, Request.ODataProperties().NextLink, Request.ODataProperties().TotalCount ); }
Js
var xhr = new XMLHttpRequest(); xhr.open("GET", "//localhost:4931/api/salesmans?$count=true", true); //$count=true 是 odata v4. v3 是$inlinecount=allpages xhr.setRequestHeader("accept", "application/json"); xhr.send(null);