哈囉大家好!今天要正式開始寫扣了~
要練習的是如何撰寫API格式!
首先要先啟動專案,移動到.csproj檔的路徑位置,在終端機執行指令dotnet run
。
如果專案中有多個.csproj檔,執行時可以指定要執行的project: dotnet run --project anotherProject.csproj
(註:--project後面接的是指定project檔的路徑字串喔!)
更多執行時的指令設定也可以參考官方文檔!
執行完指令後,do re mi so~~
可以在終端機看到"Now listening on http://localhost:5232" 的訊息,接著在瀏覽器打開這個URL, 就可以在畫面中看到Program.cs檔中"/"路徑回傳的"Hello World!"
會顯示listening on http://localhost:5232 是因為這個url就是在launchSettings.json檔中設定的applicationUrl:
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5232",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
再來看一眼目前預設的Program.cs檔:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Run();
此處設置路徑時,用到了MapGet(MapMethod) method來處理GET request。除了GET之外,也支援其他HTTP method,例如POST, PUT, DELETE。更詳細的使用說明也可以在官方文檔找到~
接下來我也試試看加一個簡單的GET Request:
app.MapGet("/test", () => "Hey hey!");
這裡有個重要的地方!重新編輯儲存檔案後,必須中斷目前程式碼的執行,再重新跑一次 dotnet run 才能看到更新結果。
如果不想要每次都手動重新啟動,可以執行另一個指令:dotnet watch run
!
只要儲存檔案,就會自動重新編譯,超級方便快速~~
之後就可以在瀏覽器輸入API endpoint: http://localhost:5232/test
就可以看到:
"hey hey!"
除了直接在 MapGet 裡寫 lambda,也可以將處理函式(handler)另外抽出來
var handler = () => "Hey hey!";
app.MapGet("/test", handler);
這裡示範的是lambda expression, 根據官方文檔也可以寫成local function, instance method, static method, 可以根據專案需求選擇適合的寫法~
除此之外,也可以在路徑中帶入參數:
app.MapGet("/ithomeIron/{year}/members/{memberId}",
(int year, int memberId) => $"Your member id is {memberId}, participating Ithome Iron in {year}!");
在瀏覽器輸入API endpoint:(帶入 year 和 memberId,例如) http://localhost:5232/ithomeIron/2025/members/1234
就可以看到:
"Your member id is 1234, participating Ithome Iron in 2025!"
註:測試時用dotnet watch run啟動專案,有出現更新完檔案後在瀏覽器顯示異常的情況。
上網查了一下,有可能是因為dotnet watch run的hot reload並沒有正確更新路由表(route table)。
這時候就可以重新中斷執行並重新啟動,確保API endpoint有被正確設置!
今天簡單介紹了Web API的撰寫格式,明天要來試試看用免費的public API發送GET request和POST request