在ASP.NET Core中,處理數據刪除通常涉及到以下幾個步驟:
ProductsController的控制器。using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
// ...
}
using System.Linq;
using Microsoft.EntityFrameworkCore;
// ...
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(int id)
{
// ...
}
Product的實體類和一個名為ProductsContext的DbContext類。// ...
private readonly ProductsContext _context;
public ProductsController(ProductsContext context)
{
_context = context;
}
// ...
// ...
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(int id)
{
var product = await _context.Products.FindAsync(id);
if (product == null)
{
return NotFound();
}
_context.Products.Remove(product);
await _context.SaveChangesAsync();
return NoContent();
}
現在,當客戶端發送一個DELETE請求到/api/products/{id}時,Delete方法將從數據庫中刪除具有指定ID的產品。如果找不到該產品,將返回404 Not Found響應。如果成功刪除產品,將返回204 No Content響應。