
深入解析API网关策略:认证、授权、安全、流量处理与可观测性
在 RESTful Web API 开发中,DELETE 请求用于删除服务器上的资源。结合 Repository 模式,能将数据访问集中到仓储层,保持控制器简洁、易测试。本文以“分类(Category)”“国家(Country)”“所有者(Owner)”等实体为例,演示如何在 ASP.NET Core 中优雅地实现 DELETE 操作。
项目结构:
/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
在各自的仓储接口中,添加删除方法签名。例如,ICategoryRepository
:
public interface ICategoryRepository
{
bool DeleteCategory(Category category);
bool CategoryExists(int categoryId);
}
> 提示:DeleteXxx
返回布尔值,指示删除是否成功;同时保留 Exists
方法用于前置校验。
在 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
方法。
以 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
}
}
CategoryExists
确认资源存在,否则返回 404 Not Found
。400 Bad Request
并给出错误说明。204 No Content
,符合 REST 规范。当要删除多条关联数据(如某 Pokémon 下所有评论)时,可在仓储中使用 RemoveRange
:
public bool DeleteReviews(IEnumerable < Review > reviews)
{
_context.RemoveRange(reviews);
return _context.SaveChanges() > 0;
}
在控制器中先通过 GetReviewsByPokemon(pokemonId)
拿到列表,再传入此方法即可一次性批量删除。
https://localhost:5001/swagger
)。categoryId = 8
),点击 “Execute”。验证响应:
Exists
方法或异常捕获,避免删除不存在的实体。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