本篇實現F3功能(見紅色部分)
| 功能序號 | HTTP謂詞(HTTP verbs) | API | 描述 |
| F1 | GET | /api/users |
管理員獲取用戶列表 |
| F2 | POST | /api/users |
管理員添加用戶 |
| F3 | PATCH | /api/users/{id}/role | 管理員修改用戶角色 |
| F4 | PATCH | /api/users/{id}/state | 管理員鎖定/解鎖用戶 |
| F5 | GET | /api/users/{id} | 用戶獲取自己的信息 |
| F6 | PUT | /api/users/{id} | 用戶更新自己的信息 |
| F7 | PATCH | /api/users/{id} |
用戶修改密碼 |
在此功能中使用的HTTP謂詞是PATCH,而鎖定/解鎖用戶及修改密碼也是同樣的謂詞,
所以我們需要給終結點添加Route屬性加以區分,以便讓路由系統能正確的匹配到。
在.net core webapi中,Controller和Endpoint都可以添加Route屬性,如果都添加,其路由是疊加關系。
比如UsersController的Route屬性設置成[Route("api/[controller]")] , 某個Endpoint的Route屬性設置成[Route("role")] ,
那么組合而成的路由就是api/[controller]/role,訪問網址http://localhost:52384/api/users/role就能匹配到該Endpoint上。
先看代碼:
1 [HttpPatch] 2 [Route("{id}/role")] 3 public ContentResult ManageRole(int id) 4 { 5 int roleCode = Convert.ToInt32(Request.Query["roleCode"]); 6 _userDao.UpdateUserRole(id, roleCode); 7 8 return Content("{'result':'success'}"); 9 }
1. 因為只是更新t_user表的部分字段,所以這里的HTTP謂詞用HttpPatch
2.終結點ManageRole( )中的形參id是和[Route("{id}/role")]中的id對應的,
是從網址中傳遞過來的,是一個變量,所以用{ }括起來,本例中客戶端調用的網址就是:
http://localhost:52384/api/users/2/role?rolecode=2,
路由會將api/users匹配給UsersController上的Route,2/role匹配給終結點ManageRole(int id)上的Route;
需要注意的是[Route("{id}/role")]前面千萬不要加"/",因為"/"表示根路徑,寫成[Route("/{id}/role")]是錯誤的。
3.網址后的查詢參數roleCode=2在終結點ManageRole( )中除了可以用Request.Query["roleCode"]接收外,
還可以用[fromQuery]屬性來獲取,這樣ManageRole( )需要做相應的修改,代碼如下:
1 [HttpPatch] 2 [Route("{id}/role")] 3 public ContentResult ManageRole(int id, [FromQuery] int roleCode) 4 { 5 //int roleCode = Convert.ToInt32(Request.Query["roleCode"]); 6 7 _userDao.UpdateUserRole(id, roleCode); 8 9 return Content("{'result':'success'}"); 10 }
注:ManageRole( )中的形參roleCode一定要和網址
http://localhost:52384/api/users/2/role?rolecode=2中的查詢參數名稱相同,否則是獲取不到值的。
