
微軟翻譯API密鑰獲取、API對接實戰指南
項目結構:
/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