ASP.NET Core Web API DELETE 请求实战|Repository 模式下的删除操作详解
作者:xiaoxin.gao · 2025-07-02 · 阅读时间:5分钟
1. 引言 在 RESTful Web API 开发中,DELETE 请求用于删除服务器上的资源。结合 Rep […]
文章目录
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);
}
同理,为 CountryRepository
、OwnerRepository
等分别实现 DeleteCountry
、DeleteOwner
方法。
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 测试流程
- 运行项目,打开 Swagger UI(如
https://localhost:5001/swagger
)。 - 找到对应 DELETE 方法,点击 “Try it out”。
- 填写路径参数(例如
categoryId = 8
),点击 “Execute”。 -
验证响应:
- 204 No Content:删除成功
- 404 Not Found:资源不存在
- 在 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
热门推荐
一个账号试用1000+ API
助力AI无缝链接物理世界 · 无需多次注册
3000+提示词助力AI大模型
和专业工程师共享工作效率翻倍的秘密
热门API
- 1. AI文本生成
- 2. AI图片生成_文生图
- 3. AI图片生成_图生图
- 4. AI图像编辑
- 5. AI视频生成_文生视频
- 6. AI视频生成_图生视频
- 7. AI语音合成_文生语音
- 8. AI文本生成(中国)