一、路由約束(URL Constraints)——簡單類型校驗

  1. 原理
    路由約束可以在路由模板中指定參數類型,例如 {id:int},如果傳入非整數會直接返回 404。

  2. 實現步驟
    在 Controller 的路由屬性中添加類型約束:

    [HttpGet("{id:int}")]
    public async Task < ActionResult < Comment > > GetCommentAsync(int id)
    {
       // ...
    }

    同理,DELETE、PUT 等帶 ID 的路由也可加上 :int

  1. 驗證
    使用 Swagger 或直接在瀏覽器地址欄輸入非數字,如 GET /api/comment/abc,將返回 404。

二、DTO 中的 DataAnnotations——復雜類型校驗

  1. 為何用 DTO
    將校驗屬性放在專用 DTO 上,避免在實體模型中混入校驗邏輯,保持關注點分離。

  1. 添加校驗特性
    在 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; }
    }

  1. 對其他 DTO 重復同樣操作


三、在 Controller 中啟用 ModelState 校驗

  1. 檢查 ModelState
    在每個接收 DTO 的端點頂部添加:

    if (!ModelState.IsValid)
       return BadRequest(ModelState);

    這樣一來,框架會根據 DTO 上的 DataAnnotations 自動校驗,并在失敗時返回 400 錯誤及詳細信息。

  1. 示例:CreateCommentAsync

    [HttpPost]
    public async Task < ActionResult < Comment > > CreateCommentAsync(CreateCommentRequest dto)
    {
       if (!ModelState.IsValid)
           return BadRequest(ModelState);
    
       // 創建邏輯...
    }

四、測試與驗證

  1. 路由約束測試

  1. DTO 校驗測試


小結

通過以上方法,可有效提升 API 的健壯性與安全性。下一步可探索全局過濾器(Action Filter)、自定義校驗屬性等更高級的校驗機制。

原文引自YouTube視頻:https://www.youtube.com/watch?v=1i_WE4aGVLU

上一篇:

REST API 基礎:定義、示例及使用方法

下一篇:

ASP.NET Core Web API 快速集成 Entity Framework Core:從安裝到數據預熱全流程
#你可能也喜歡這些API文章!

我們有何不同?

API服務商零注冊

多API并行試用

數據驅動選型,提升決策效率

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

對比大模型API的內容創意新穎性、情感共鳴力、商業轉化潛力

25個渠道
一鍵對比試用API 限時免費

#AI深度推理大模型API

對比大模型API的邏輯推理準確性、分析深度、可視化建議合理性

10個渠道
一鍵對比試用API 限時免費