九.OData(Open Data Protocol)

作者使用的是實體Entities,似乎不是使用SQL Query去做查詢,這樣查詢並不會節省SQL的資源,所以先略過此章節的學習...

[Queryable]
[GET("allproducts")]
[GET("all")]
public HttpResponseMessage Get()
{
    //待查證目的性-為何要用實體轉為Queryable,而不直接使用Queryable?
    var products = _productServices.GetAllProducts().AsQueryable();
    var productEntities = products as List<ProductEntity> ?? products.ToList();
    if (productEntities.Any())
        return Request.CreateResponse(HttpStatusCode.OK, productEntities.AsQueryable());
    throw new ApiDataException(1000, "Products not found", HttpStatusCode.NotFound);
}

---以下為舊內容

OData是一種提供查詢REST服務彈性的協義,它讓你可以透過Http與Server溝通對資料做CRUD,例如說可在查詢的Uri加入$orderby參數將資料做排序:

http://localhost/Products?$orderby=Name

查詢方式

  • $orderby
  • 排序特定欄位,可指定ascendingdescending
  • $select
  • 查詢特定欄位
  • $skip
  • 略過前N筆資料
  • $top
  • 取得前N筆資料
  • $expand
  • 額外取得其它作者使用的是實體Entities
  • $filter
  • 篩選資料,等同於,似乎不是使用SQL中的Where
  • $inlinecount
  • 分頁

啟用OData

移到主專案的資料夾底下

加入Nuget

  • Microsoft.AspNet.WebApi.OData

登入方式

必須先取得登入的Token,才有權限進入後續的操作,方式如下:

在Header上加入下列資訊去取得授權後的Token

Key Value
Authorization Basic YWtoaWw6YWtoaWw=

Authorization中所傳入的Base64編碼(YWtoaWw6YWtoaWw=)解密後為 akhil:akhil,正好是資料庫內User資料表的其中一筆資料 Query去做查詢,所以先略過此章節的學習...

results matching ""

    No results matching ""