Contact Manager Web API 示例[3] 分頁和查詢(Paging and Querying)
聯(lián)系人管理器web API是一個Asp.net web api示例程序,演示了通過ASP.NET Web API 公開聯(lián)系信息,并允許您添加和刪除聯(lián)系人,示例地址http://code.msdn.microsoft.com/Contact-Manager-Web-API-0e8e373d。
Contact Manager Web API 示例[1]CRUD 操作 已經(jīng)做了一個基本的介紹,
Contact Manager Web API 示例[2] Web API Routing 介紹Web API Routing。
本文主要介紹OData的查詢和分頁支持。
OData開放數(shù)據(jù)協(xié)議是微軟針對Google的GData推出的,旨在推廣Web程序數(shù)據(jù)庫格式標準化的開放數(shù)據(jù)協(xié)議,微軟將 OData 定義為基于 HTTP、AtomPub 和 JSON 的協(xié)議,增強各種網(wǎng)頁應(yīng)用程序之間的數(shù)據(jù)兼容性,以提供多種應(yīng)用、服務(wù)和數(shù)據(jù)商店的信息訪問。
Open Data Protocal (OData) 指定查詢字符串參數(shù)讓 Client 能使用它去排序與過濾結(jié)果。
Web API 提供以下支持 OData 查詢參數(shù):
| Web API 提供支持 OData 查詢參數(shù) | ||
| 查詢參數(shù) | 說明 | 范例 |
| $filter | 選擇與布爾表達式相符的項目 | http://localhost:port/api/contacts?$filter=substringof(Name, 'Ed') eq true |
| $orderby | 指定的屬性來排序結(jié)果 | http://localhost:port/api/contacts?$orderby=Name |
| $skip | 跳過前 n 筆元素 | http://localhost:port/api/contacts?$skip=2 |
| $top | 傳回前 n 筆元素 | http://localhost:port/api/contacts?$orderby=Name |
$top 如果與 $orderby 一起使用,會先排序,然后再取得前 n 筆元素以返回。
例如,以下的 URI 會回傳前 3 筆聯(lián)系人數(shù)據(jù),而且使用 name 排序過。
http://localhost:port/api/contacts?$top=3&orderby=name
要支持這些查詢選項,簡單的從 GET 方法中回去 IQueryable 類型和Queryable attribute (System.Web.Http.QueryableAttribute).
。例如我們把
[Queryable(ResultLimit=20)]
public IQueryable<Contact> Get()
{
return this.repository.GetAll().AsQueryable();
}
只需要通過 .AsQueryable() 的幫忙,即可幫我們轉(zhuǎn)換。
更多 OData 查詢字符串參數(shù)信息,請查詢 OData: URI Conventions。
參考數(shù)據(jù)
歡迎大家掃描下面二維碼成為我的客戶,扶你上云

浙公網(wǎng)安備 33010602011771號