ASP.NET - Get started with WebApi

Create a service

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public string Category { get; set; }
}

public class ProductsController : ApiController
{
    static List<Product> _products = CreateProducts().ToList();
 
    static Product[] CreateProducts()
    {
        return new Product[] {
            new Product() {
                Id = 1,
                Name = "Apple",
                Price = 5.8M,
                Category = "Fruit"
            },
            new Product() {
                Id = 2,
                Name = "Orange",
                Price = 3.5M,
                Category = "Fruit"
            }
        };
    }
         
    // GET: api/Products

    public IEnumerable<Product> Get()
    {
        return _products;
    }
 
    // GET: api/Products/5

    public Product Get(int id)
    {
        foreach (var p in _products) {
            if (p.Id == id) {
                return p;
            }
        }
        return null;
    }
 
    public void Post(Product product)
    {
        _products.Add(product);
    }
}

Create a client

class Program
{
    static HttpClient _hc = CreateHttpClient();
 
    static HttpClient CreateHttpClient()
    {
        var hc = new HttpClient();
        hc.BaseAddress = new Uri("http://localhost:49735/");
        return hc;
    }
 
    static async Task ListAllProducts()
    {
        var resp = await _hc.GetAsync("/api/products");
        if (resp.IsSuccessStatusCode) {
            var products = await resp.Content.ReadAsAsync<IEnumerable<Product>>();
            Console.WriteLine("--------------------------");
            foreach (var p in products) {
                Console.WriteLine($"{p.Id} {p.Name} {p.Price} {p.Category}");
            }
        }
    }
 
    static void Main(string[] args)
    {
        Task.Run(async () => {
            await ListAllProducts();
            var resp = await _hc.PostAsJsonAsync<Product>("/api/products", new Product() {
                Id = 3,
                Name = "Egg",
                Price = 5.5M,
                Category = "Unknown"
            });
            await ListAllProducts();
        }).Wait();
    }
}

Output

--------------------------
1 Apple 5.8 Fruit
2 Orange 3.5 Fruit
--------------------------
1 Apple 5.8 Fruit
2 Orange 3.5 Fruit
3 Egg 5.5 Unknown