Controllers – Get

אחרי שראינו מה הדרך הנכונה לבנות controller, ננקה את ה-controller ונראה מה יש לנו בו.

קובץ ProductsController.cs

[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
    private readonly IProductsRepository _productRepository;

    public ProductsController(IProductsRepository productRepository) {
        _productRepository = productRepository;
    }

    [HttpGet]
    public async Task<ActionResult<List<Product>>> Get() {
        var result = await _productRepository.GetAllProducts();
        return Ok(result);
    }
}

יש את הפונקציה get שמביאה לנו את רשימת המוצרים. נממש את הפונקציונליות עבור פעולות אחרות.

הבאת פריט בודד

למוצר בודד הנתיב יהיה משהו כמו: api/products/23. ניצור את הפונקציה המתאימה. אנחנו יכולים להוסיף לפונקציה גם מה סוג הנתונים שאנחנו מתכוונים לקבל ממנה, למשל 200, שזה תקין, עם מוצר או 404 שזה לא נמצא המוצר במקרה של id לא תקין.

כמו כן נצטרך לייצר את הפונקציה שמביאה בפועל את המידע.

קובץ IProductsRepository.cs

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

קובץ ProductsController.cs

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

יכול להיות שיחזור לנו null וצריך לאפשר את זה ברמת הקומפילציה בפונקציה עצמה, את זה נעשה על ידי הוספת ? לערך המוחזר.

קובץ IProductsRepository.cs

Task<Product?> GetProductById(int id);

עכשיו נבדוק את הערך המוחזר ונבצע פעולות בהתאם.

קובץ ProductsController.cs

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

מכיוון שאנחנו כרגע לא מול DB נדמה את הפעולה על ידי יצירת list ב-constructor של ProductsRepository. נשתמש ב-Delay כדי לדמות פעולת DB.

קובץ ProductsRepository.cs

public class ProductsRepository : IProductsRepository
{
    private readonly List<Product> _products = new List<Product>();
    public ProductsRepository() {
        _products.Add(new Product 
        {
                id = 1,
                name = "ASUS Computer",
                description = "Best computer",
                price = 2400,
                amount = 4,
                producer = "Asus"
        });
    }
    public async Task<List<Product>> GetAllProducts() {
        await Task.Delay(1000);
        return _products;
    }

    public async Task<Product?> GetProductById(int id) {
        await Task.Delay(500);
        var item = this._products.FirstOrDefault(x => x.id == id);
        if(item == null) {
            return null;
        }
        return item;
    }
}

ניווט במאמר

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

Weekly Tutorial