Routing Tables, 路由表
在 ASP.NET Web API,一個 controller 是一個 class(類別) 以處理 HTTP 請求(requests)。在 controller 裡所有的公開方法(public methods)都稱為 Action方法 或簡稱 Action。當 Web API Framework 接收到一個請求,它路由請求到一個 Action。Framework 會使用路由表(Routing Table),決定那一個 Action 會被呼叫。如果你在 ASP.NET 裡使用 Web API,路由表會定義在 Global.asax 檔案中。預設使用 Visual Studio 去新增一個 Web API 專案,專案樣版會建立預設路由給你:
routes.MapHttpRoute( _ name:="DefaultApi", _ routeTemplate:="api/{controller}/{id}", _ defaults:=New With {.id = RouteParameter.Optional} _ )
注意,如果你使用 self-host Web API,你必須在 HttpSelfHostConfiguration物件 上直接設定路由表(這未來我們會討論)。每個實體(entry)在路由表裡都包含一個路由樣板(route template)。Web API 的路由樣板預設是 "api/{controller}/{id}",此樣板裡,"api" 是文字路徑片段,{controller} 和 {id} 是定位變數。
當 Web API Framework 接收到一個 HTTP 請求,它會去嘗試比對 URI 對路由表的路由樣板之一, 如果沒有符合的路由,Client 會收到一個 404 錯誤。例如,以下 URI 會符合預設路由:
- /api/contacts
- /api/contacts/1
- /api/products/ApplePie