[英]Best implementation of a searchable GET endpoint in ASP.NET Web Api
我有一個WebApi,它在數據庫中公開了一個Contact字段。 當前,它具有Post(創建),Put(編輯),Get(返回整個列表),Get(整數id)(返回特定字段)的端點。
因此,Get(int id)在我的數據庫中搜索具有該ID的聯系人,並以JSON返回。 我想實現一種方法,用戶可以通過該方法向我的第一個Get函數提交條件,例如:
GET http://urlformyapi.com/api/apiContact/?querystring
查詢字符串可能是例如:
firstname=phil
並歸還所有的Phil。
如何最好地使其完全可搜索聯系人中的所有數據字段?
public int contactid { get; set; }
[Required]
public string firstname { get; set; }
[Required]
public string lastname { get; set; }
[Required]
public string email { get; set; }
[Required]
public string mobile { get; set; }
public string company { get; set; }
public string position { get; set;}
public string notes { get; set; }
public string image { get; set; }
我可以對整個列表進行初始獲取,然后遍歷每個查詢參數,例如:
//where ContactList begins as the entire list of contacts.
if(notes != null){ ContactList = ContactList.Where(x => x.notes == notes).ToList(); }
因此完善我的清單,直到返回為止。 但是我想知道是否應該有一種更簡便的方法,該方法更健壯,如果我的數據模型發生更改/我想使更多字段可搜索。
有什么想法嗎?
如果您有很多類似的API方法,那么可以看看OData 。 為此,另一種嘗試使用Dynamic Linq和自定義過濾器格式的方法。 否則,我的建議是創建類,該類必須包含查詢字段(搜索字段),例如:注釋,ID等,然后將此對象傳遞給API並使用這些搜索字段和PredicateBuilder過濾您的集合。 也很好地解釋了PredicateBuilder的工作方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.