ASP.NET Web API - Route
Web API Routing
Web API 主要有 2 種 Routing 的方式
1.Routing Table
2.Attribute Routing
2.Attribute Routing
Routing Table
在 Default 中, Web API 使用的是 Route Table 的 Template
config.Routes
是一個 HttpRouteCollection 的 type, 主要是裝 Route TableMapHttpRoute
是一個 function, 可以創造一個 IHttpRoute 的 instance 並且把以下的參數加入 config.Routes 裡面
WebConfig.cs
想要有自己定義一個 Route 也是沒問題的, 甚至還可以加入限制, 我這裡舉例的是如果我有 id, 那麼這個 id 一定要至少出現一次 0-9之間的數字
WebConfig.cs
Attribute Routing : configuration, adding constraint to route parameter
使用 [Route()] 來表示 Api 的 route, 可以使用在 Controller 或者是 Action 都可以
- Configuration
如果要使用 Attribute Routing, 就要在WebConfig.cs
裡面 registerconfig.MapHttpAttributeRoutes();
- 在 Controller 裡面就可以這樣使用, 以下的這個 Route 會和 /api/employees 是一樣的
- 這一個 Route 就會和 /api/employees/1 是一樣的
Route Prefix
可以看到上面 2 個例子都有 /api/employees, 那麼我們就可以用 RoutePrefix, RoutePrefix 顧名思義就是把相同的 String 放在 class的上面, 表示這一整個 class 是屬於 /api/employees, 那麼把每一個 function 所使用的 /api/employees 刪除就可以
- 那麼突然有一天我想要 override 這一個 route 要怎麼辦? 只要在前面加上
~
就可以了
[RoutePrefix("api/books")]
public class BooksController : ApiController
{
// GET /api/authors/1/books
[Route("~/api/authors/{authorId:int}/books")]
public IEnumerable<Book> GetByAuthor(int authorId) { ... }
// ...
}
留言
張貼留言