Controllers – Delete

כדי לממש delete משתמשים ב-HttpDelete. שאר ה-URL זהה. לפני שאנחנו מוחקים אנחנו רוצים לבדוק שהמוצר קיים.

קובץ ProductsController.cs

[HttpDelete("{id}")]
[ProducesResponseType(200, Type = typeof(Product))]
[ProducesResponseType(404)]
public async Task<ActionResult<Product>> DeleteProduct(int id) {
    var result = await _productRepository.GetProductById(id);
    if (result == null) {
        return NotFound();
    }
    await _productRepository.DeleteProduct(id);
    return Ok(result);
}

נוסיף את הפונקציה ל-interface.

קובץ IProductsRepository.cs

public interface IProductsRepository
{
    Task<List<Product>> GetAllProducts();
    Task<Product?> GetProductById(int id);
    Task DeleteProduct(int id);
}

ונממש אותה.

קובץ ProductsRepository.cs

public async Task DeleteProduct(int id) {
    await Task.Delay(500);
    var item = this._products.FirstOrDefault(x => x.id == id);
    if(item != null) {
        this._products.Remove(item);
    }
}

ניווט במאמר

מאמרים אחרונים

Weekly Tutorial