影片講解(有字幕)
這篇文章要來說說,如果要做關鍵字搜尋的API該怎麼實作呢?
那通常我們會用GET傳參數的方法來傳遞需要過濾的關鍵字,那GET方法該如何傳遞參數呢?有做過網站的人一定知道,就是在網址結尾處加個?後面並使用&就可以串你的參數了。
例如:api/todo?id=xxxx&id2=xxxx
其中id是你欄位名稱,xxxx則是你的參數,然後有多個參數可以用&來做隔開,那有了這個基礎知識後,我們就要來開始串參數瞜。
首先我的TodoList資料表我打算針對name、enable和InsertTime做過濾,所以在網址的部分我們可以這樣下,api/todo?name=xxxx&enable=xxxx&InsertTime=xxxx
。
那在我們程式中該如何接收到這三個值(xxxx部分)呢?
這是上一節撈取全部資料的API,再加上接收參數的程式碼:
[HttpGet]
public IEnumerable<TodoListSelectDto> Get(string name, bool? enable, DateTime? InsertTime)
{
var result = _todoContext.TodoLists
.Select(a => new TodoListSelectDto
{
Enable = a.Enable,
InsertEmployeeName = a.InsertEmployee.Name,
InsertTime = a.InsertTime,
Name = a.Name,
Orders = a.Orders,
TodoId = a.TodoId,
UpdateEmployeeName = a.UpdateEmployee.Name,
UpdateTime = a.UpdateTime
});
return result;
}
我們會在這支函式接受參數的地方打上對應的欄位名稱和型別,其中在型別後面加?是表示這個參數不一定會有值過來,如果沒有值傳過來就會是null,因為我們關鍵字搜尋並不一定每個欄位都要做過濾,常常會是部分過濾而已,因此沒傳值的就讓它等於null好讓我們做後續的判斷,那其中string沒傳值時會是空字串,所以不用加也不能加。
接著我們就要來寫過濾的程式了,首先一樣先撈出全部,但撈出全部後我們一個一個參數來做判斷過濾。
先判斷name是不是空白或空值,如果是我們就進行過濾,那我們這邊就是將一開始撈到的全部結果,再進行二次條件過濾result.Where(a => a.Name.Contains(name))
,那a.Name.Contains(name)
就是找尋Name欄位有沒有符合傳來的參數name的資料,有的話則留下來。
if (!string.IsNullOrWhiteSpace(name))
{
result = result.Where(a => a.Name.Contains(name));
}
接著再判斷enable如果不是null的話,就進行過濾,寫法如下。
if (enable != null)
{
result = result.Where(a => a.Enable == enable);
}
最後就判斷InsertTime如果不是null的話,也進行過濾,寫法如下。
if (InsertTime != null)
{
result = result.Where(a => a.InsertTime.Date == InsertTime);
}
那這樣經過三次判斷後,最後的result就會是我們所搜尋符合結果的資料了。
改造完原有的撈取全部資料後的程式碼:
[HttpGet]
public IEnumerable<TodoListSelectDto> Get(string name, bool? enable, DateTime? InsertTime)
{
var result = _todoContext.TodoLists
.Select(a => new TodoListSelectDto
{
Enable = a.Enable,
InsertEmployeeName = a.InsertEmployee.Name,
InsertTime = a.InsertTime,
Name = a.Name,
Orders = a.Orders,
TodoId = a.TodoId,
UpdateEmployeeName = a.UpdateEmployee.Name,
UpdateTime = a.UpdateTime
});
if (!string.IsNullOrWhiteSpace(name))
{
result = result.Where(a => a.Name.Contains(name));
}
if (enable != null)
{
result = result.Where(a => a.Enable == enable);
}
if (InsertTime != null)
{
result = result.Where(a => a.InsertTime.Date == InsertTime);
}
return result;
}
這樣子當沒有任何參數時,依然會正常撈取全部資料,那有參數時就會進行過濾,是不是很簡單呢?想看更完整的流程可以看影片。
新手分享學習成果,若有錯誤,煩請告知修正,感謝🙏
範例檔下載:下載