通过HttpClient 调用ASP.NET Web API

时间:2021-09-21 07:59:31

public class ProductsController : ApiController { // Mock product list public static List<Product> productList =http://www.mamicode.com/ initProductMockDataList(); private static List<Product> initProductMockDataList() { return new List<Product>() { new Product {ProductID=http://www.mamicode.com/1,ProductName=http://www.mamicode.com/"Product A",Price=http://www.mamicode.com/1000000,Count=http://www.mamicode.com/5,Description=http://www.mamicode.com/"Description A"}, new Product {ProductID=http://www.mamicode.com/2,ProductName=http://www.mamicode.com/"Product B",Price=http://www.mamicode.com/200000,Count=http://www.mamicode.com/2,Description=http://www.mamicode.com/"Description B"}, new Product {ProductID=http://www.mamicode.com/3,ProductName=http://www.mamicode.com/"Product C",Price=http://www.mamicode.com/500000,Count=http://www.mamicode.com/8,Description=http://www.mamicode.com/"Description C"}, new Product {ProductID=http://www.mamicode.com/4,ProductName=http://www.mamicode.com/"Product D",Price=http://www.mamicode.com/80000,Count=http://www.mamicode.com/10,Description=http://www.mamicode.com/"Description D"}, new Product {ProductID=http://www.mamicode.com/5,ProductName=http://www.mamicode.com/"Product E",Price=http://www.mamicode.com/300000,Count=http://www.mamicode.com/3,Description=http://www.mamicode.com/"Description E"} }; } public IEnumerable<Product> Get() { return productList; } public Product Get(int id) { return productList.Where(p => p.ProductID ==http://www.mamicode.com/ id).FirstOrDefault(); } public void Post([FromBody]Product product) { var lastProduct = productList.OrderByDescending(p => p.ProductID).FirstOrDefault(); int newProductID = lastProduct.ProductID + 1; product.ProductID =http://www.mamicode.com/ newProductID; productList.Add(product); } public void Put([FromBody]Product product) { var currentProduct = productList.Where(p => p.ProductID ==http://www.mamicode.com/ product.ProductID).FirstOrDefault(); if (currentProduct != null) { foreach (var item in productList) { if (item.ProductID.Equals(currentProduct.ProductID)) { item.ProductName =http://www.mamicode.com/ product.ProductName; item.Price =http://www.mamicode.com/ product.Price; item.Count =http://www.mamicode.com/ product.Count; item.Description =http://www.mamicode.com/ product.Description; } } } } public void Delete(int id) { Product product = productList.Where(p => p.ProductID ==http://www.mamicode.com/ id).FirstOrDefault(); productList.Remove(product); } }