2. 前置條件與項目結構


3. 定義 DELETE 接口簽名

在各自的倉儲接口中,添加刪除方法簽名。例如,ICategoryRepository

public interface ICategoryRepository
{
    bool DeleteCategory(Category category);
    bool CategoryExists(int categoryId);
}

> 提示DeleteXxx 返回布爾值,指示刪除是否成功;同時保留 Exists 方法用于前置校驗。


4. 倉儲層:實現刪除方法

CategoryRepository 中實現接口:

public class CategoryRepository : ICategoryRepository
{
    private readonly AppDbContext _context;
    public CategoryRepository(AppDbContext context) = > _context = context;

    public bool DeleteCategory(Category category)
    {
        _context.Remove(category);
        return _context.SaveChanges() > 0;
    }

    public bool CategoryExists(int categoryId) = >
        _context.Categories.Any(c = > c.Id == categoryId);
}

同理,為 CountryRepositoryOwnerRepository 等分別實現 DeleteCountryDeleteOwner 方法。


5. 控制器層:實現 DELETE Endpoint

CategoryController 為例:

[ApiController]
[Route("api/[controller]")]
public class CategoryController : ControllerBase
{
    private readonly ICategoryRepository _repo;
    public CategoryController(ICategoryRepository repo) = > _repo = repo;

    [HttpDelete("{categoryId}")]
    [ProducesResponseType(204)]
    [ProducesResponseType(404)]
    public IActionResult DeleteCategory(int categoryId)
    {
        // 5.1 參數校驗與實體存在性檢查
        if (!_repo.CategoryExists(categoryId))
            return NotFound($"Category {categoryId} not found.");

        var category = _repo.GetCategory(categoryId); // 假設已有此方法

        // 5.2 調用倉儲刪除并返回狀態碼
        if (!_repo.DeleteCategory(category))
            return BadRequest("刪除失敗,請稍后重試。");

        return NoContent(); // HTTP 204
    }
}

5.1 參數校驗與實體存在性檢查

5.2 調用倉儲刪除并返回狀態碼


6. 全表刪除(Delete Range)示例

當要刪除多條關聯數據(如某 Pokémon 下所有評論)時,可在倉儲中使用 RemoveRange

public bool DeleteReviews(IEnumerable < Review > reviews)
{
    _context.RemoveRange(reviews);
    return _context.SaveChanges() > 0;
}

在控制器中先通過 GetReviewsByPokemon(pokemonId) 拿到列表,再傳入此方法即可一次性批量刪除。


7. Swagger 測試流程

  1. 運行項目,打開 Swagger UI(如 https://localhost:5001/swagger)。
  2. 找到對應 DELETE 方法,點擊 “Try it out”。
  3. 填寫路徑參數(例如 categoryId = 8),點擊 “Execute”。
  4. 驗證響應:

  5. Responses 區域查看返回值,并可在數據庫中驗證記錄已被移除。

8. 小結與最佳實踐

通過本文示例,你已掌握在 ASP.NET Core Web API 中,結合 Repository 模式實現 DELETE 請求的核心技巧與最佳實踐,讓你的 API 更加健壯、可測試。祝開發順利!

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

上一篇:

C# .NET Core API 創建方法詳解|Entity Framework 多對多關系實戰

下一篇:

如何通過WhatsApp API實現業務自動化 | 增強客戶互動與銷售
#你可能也喜歡這些API文章!

我們有何不同?

API服務商零注冊

多API并行試用

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

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

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

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

#AI深度推理大模型API

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

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