所有文章 > 如何集成API > ASP.NET Core Web API DELETE 请求实战|Repository 模式下的删除操作详解
ASP.NET Core Web API DELETE 请求实战|Repository 模式下的删除操作详解

ASP.NET Core Web API DELETE 请求实战|Repository 模式下的删除操作详解

1. 引言

在 RESTful Web API 开发中,DELETE 请求用于删除服务器上的资源。结合 Repository 模式,能将数据访问集中到仓储层,保持控制器简洁、易测试。本文以“分类(Category)”“国家(Country)”“所有者(Owner)”等实体为例,演示如何在 ASP.NET Core 中优雅地实现 DELETE 操作。


2. 前置条件与项目结构

  • 技术栈:ASP.NET Core 6+、C#、Entity Framework Core
  • 项目结构

    /Interfaces
    ICategoryRepository.cs
    ICountryRepository.cs
    IOwnerRepository.cs
    IPokemonRepository.cs
    IReviewRepository.cs
    IReviewerRepository.cs
    /Repositories
    CategoryRepository.cs
    CountryRepository.cs
    OwnerRepository.cs
    PokemonRepository.cs
    ReviewRepository.cs
    ReviewerRepository.cs
    /Controllers
    CategoryController.cs
    CountryController.cs
    OwnerController.cs
    PokemonController.cs
    ReviewController.cs
    ReviewerController.cs
    /Data
    AppDbContext.cs

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 参数校验与实体存在性检查

  • 先调用 CategoryExists 确认资源存在,否则返回 404 Not Found
  • 获取实体对象后再执行删除,避免直接构造空对象。

5.2 调用仓储删除并返回状态码

  • 删除失败时可返回 400 Bad Request 并给出错误说明。
  • 删除成功返回 204 No Content,符合 REST 规范。

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. 验证响应:

    • 204 No Content:删除成功
    • 404 Not Found:资源不存在
  5. Responses 区域查看返回值,并可在数据库中验证记录已被移除。

8. 小结与最佳实践

  • Repository 模式:删除操作与其他 CRUD 操作同样集中在仓储层,保证控制器简洁。
  • 前置校验:使用 Exists 方法或异常捕获,避免删除不存在的实体。
  • HTTP 状态码:删除成功返回 204 No Content,失败或资源缺失分别返回 400/404
  • 批量删除:对一组实体可使用 RemoveRange,性能更优。
  • 依赖注入:在 Program.cs 中注册所有仓储服务:

    builder.Services.AddScoped < ICategoryRepository, CategoryRepository > ();
    // … 其他仓储注册

通过本文示例,你已掌握在 ASP.NET Core Web API 中,结合 Repository 模式实现 DELETE 请求的核心技巧与最佳实践,让你的 API 更加健壮、可测试。祝开发顺利!

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

#你可能也喜欢这些API文章!

我们有何不同?

API服务商零注册

多API并行试用

数据驱动选型,提升决策效率

查看全部API→
🔥

热门场景实测,选对API

#AI文本生成大模型API

对比大模型API的内容创意新颖性、情感共鸣力、商业转化潜力

25个渠道
一键对比试用API 限时免费

#AI深度推理大模型API

对比大模型API的逻辑推理准确性、分析深度、可视化建议合理性

10个渠道
一键对比试用API 限时免费