
深入解析API網關策略:認證、授權、安全、流量處理與可觀測性
原理
路由約束可以在路由模板中指定參數類型,例如 {id:int}
,如果傳入非整數會直接返回 404。
實現步驟
在 Controller 的路由屬性中添加類型約束:
[HttpGet("{id:int}")]
public async Task < ActionResult < Comment > > GetCommentAsync(int id)
{
// ...
}
同理,DELETE、PUT 等帶 ID 的路由也可加上 :int
。
GET /api/comment/abc
,將返回 404。添加校驗特性
在 DTO 屬性上使用 [Required]
、[MinLength]
、[MaxLength]
、[Range]
等特性。例如對 CreateCommentRequest
:
public class CreateCommentRequest
{
[Required]
[MinLength(5, ErrorMessage = "Title must be at least 5 characters.")]
[MaxLength(280, ErrorMessage = "Title cannot exceed 280 characters.")]
public string Title { get; set; }
[Required]
[MinLength(5, ErrorMessage = "Content must be at least 5 characters.")]
[MaxLength(280, ErrorMessage = "Content cannot exceed 280 characters.")]
public string Content { get; set; }
}
對其他 DTO 重復同樣操作
UpdateCommentRequest
CreateStockRequest
(Symbol、CompanyName、PurchasePrice、Dividend、Industry、MarketCap)UpdateStockRequest
檢查 ModelState
在每個接收 DTO 的端點頂部添加:
if (!ModelState.IsValid)
return BadRequest(ModelState);
這樣一來,框架會根據 DTO 上的 DataAnnotations 自動校驗,并在失敗時返回 400 錯誤及詳細信息。
示例:CreateCommentAsync
[HttpPost]
public async Task < ActionResult < Comment > > CreateCommentAsync(CreateCommentRequest dto)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
// 創建邏輯...
}
路由約束測試
GET /api/comment/string
→ 404。DTO 校驗測試
POST /api/comment
提交短于 5 字符的 Title 或超長 Content → 返回 400 與錯誤信息。POST /api/stock
提交缺失必填字段或超出范圍的數值 → 返回 400。ModelState
進行復雜校驗。通過以上方法,可有效提升 API 的健壯性與安全性。下一步可探索全局過濾器(Action Filter)、自定義校驗屬性等更高級的校驗機制。
原文引自YouTube視頻:https://www.youtube.com/watch?v=1i_WE4aGVLU