Untitled

 avatar
Chicky
plain_text
6 months ago
2.1 kB
3
Indexable
Never
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using YourApp.Models;

namespace YourApp.Controllers
{
    public class ProductsController : ApiController
    {
        private static List<Product> products = new List<Product>
        {
            new Product { ProductId = 1, PName = "Product 1", PCost = 10.99, PQty = 100, ImageUrl = "product1.jpg" },
            new Product { ProductId = 2, PName = "Product 2", PCost = 20.49, PQty = 50, ImageUrl = "product2.jpg" },
            // Add more products as needed
        };

        [HttpGet]
        public IHttpActionResult GetProducts()
        {
            return Ok(products);
        }

        [HttpGet]
        public IHttpActionResult GetProductById(int id)
        {
            var product = products.FirstOrDefault(p => p.ProductId == id);
            if (product == null)
                return NotFound();
            
            return Ok(product);
        }

        [HttpPost]
        public IHttpActionResult AddProduct(Product product)
        {
            product.ProductId = products.Count + 1;
            products.Add(product);
            return CreatedAtRoute("DefaultApi", new { id = product.ProductId }, product);
        }

        [HttpPut]
        public IHttpActionResult UpdateProduct(int id, Product product)
        {
            var existingProduct = products.FirstOrDefault(p => p.ProductId == id);
            if (existingProduct == null)
                return NotFound();
            
            existingProduct.PName = product.PName;
            existingProduct.PCost = product.PCost;
            existingProduct.PQty = product.PQty;
            existingProduct.ImageUrl = product.ImageUrl;
            
            return Ok(existingProduct);
        }

        [HttpDelete]
        public IHttpActionResult DeleteProduct(int id)
        {
            var product = products.FirstOrDefault(p => p.ProductId == id);
            if (product == null)
                return NotFound();
            
            products.Remove(product);
            return Ok(product);
        }
    }
}
Leave a Comment